Cast FileInfo into FileSystemInfo - vb.net

I am working on modifying file copy program that used to only copy a directory to another directory. Now I want to pass both directories and files in a list for the copy to run.
For Each _fromPath In CopyList
Dim FSinfo As FileSystemInfo()
If Directory.Exists(_fromPath) Then
Dim dir As New DirectoryInfo(_fromPath)
FSinfo = dir.GetFileSystemInfos
ElseIf File.Exists(_fromPath) Then
Dim file As New FileInfo(_fromPath)
FSinfo = file
End If
CountFiles(FSinfo)
Next
Private Function CountFiles(ByVal FSInfo As FileSystemInfo()) As Boolean
This code works fine for directories. In order to pass paths to the CountFiles, they must be in FileSystemInfo. Is there anyway to get FileInfo casted as a FileSystemInfo.
I tried CType(file, FileSystemInfo) but it said Value of type 'System.IO.FileInfo' cannot be converted to '1-dimensional array of System.IO.FileSystemInfo'.

One problem is that you are trying to convert an object (FileInfo) to an ARRAY of objects (FileSystemInfo()) which is what the error message is trying to tell you. You could write an overloaded function to handle some of that:
' my Count functions return numeric values:
Private Function CountFiles(FSInfo As FileSystemInfo()) As Integer
Private Function CountFiles(FInfo As FileInfo) As Integer
Internal to them, the FileSystemInfo might call the other in a loop to avoid duplicate code, or maybe they both call a common procedure depending on how it is written.

Related

VB.NET 2010 - Extracting an application resource to the Desktop

I am trying to extract an application resource from My.Resources.FILE
I have discovered how to do this with DLL & EXE files, but I still need help with the code for extracting PNG & ICO files.
Other file types also. (If possible)
Here is my current code that works with DLL & EXE files.
Dim File01 As System.IO.FileStream = New System.IO.FileStream("C:\Users\" + Environment.UserName + "\Desktop\" + "SAMPLE.EXE", IO.FileMode.Create)
File01.Write(My.Resources.SAMPLE, 0, My.Resources.SAMPLE.Length)
File01.Close()
First things first, the code you have is bad. When using My.Resources, every time you use a property, you extract a new copy of the data. That means that your second line is getting the data to write twice, with the second time being only to get its length. At the very least, you should be getting the data only once and assigning it to a variable, then using that variable twice. You should also be using a Using statement to create and destroy the FileStream. Even better though, just call File.WriteAllBytes, which means that you don't have to create your own FileStream or know the length of the data to write. You should also not be constructing the file path that way.
Dim filePath = Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "SAMPLE.EXE")
File.WriteAllBytes(filePath, My.Resources.SAMPLE)
As for your question, the important thing to understand here is that it really has nothing to do with resources. The question is really how to save data of any particular type and that is something that you can look up for yourself. When you get the value of a property from My.Resources, the type of the data you get will depend on the type of the file you embedded in first place. In the case of a binary file, e.g. DLL or EXE, you will get back a Byte array and so you save that data to a file in the same way as you would any other Byte array. In the case of an image file, e.g. PNG, you will get back an Image object, so you save that like you would any other Image object, e.g.
Dim filePath = Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "PICTURE.PNG")
Using picture = My.Resources.PICTURE
picture.Save(filePath, picture.RawFormat)
End Using
For an ICO file you will get back an Icon object. I'll leave it to you to research how to save an Icon object to a file.
EDIT:
It's important to identify what the actual problem is that you're trying to solve. You can obviously get an object from My.Resources so that is not the problem. You need to determine what type that object is and determine how to save an object of that type. How to do that will be the same no matter where that object comes from, so the resources part is irrelevant. Think about what it is that you have to do and write a method to do it, then call that method.
In your original case, you could start like this:
Dim data = My.Resources.SAMPLE
Once you have written that - even as you write it - Intellisense will tell you that the data is a Byte array. Your actual problem is now how to save a Byte array to a file, so write a method that does that:
Private Sub SaveToFile(data As Byte(), filePath As String)
'...
End Sub
You can now which you want to do first: write code to call that method as appropriate for your current scenario or write the implementation of the method. There are various specific ways to save binary data, i.e. a Byte array, to a file but, as I said, the simplest is File.WriteAllBytes:
Private Sub SaveToFile(data As Byte(), filePath As String)
File.WriteAllBytes(filePath, data)
End Sub
As for calling the method, you need to data, which you already have, and the file path:
Dim data = My.Resources.SAMPLE
Dim folderPath = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim fileName = "SAMPLE.EXE"
Dim filePath = Path.Combine(folderPath, fileName)
SaveToFile(data, filePath)
Simple enough. You need to follow the same steps for any other resource. If you embedded a PNG file then you would find that the data is an Image object or, more specifically, a Bitmap. Your task is then to learn how to save such an object to a file. It shouldn't take you long to find out that the Image class has its own Save method, so you would use that in your method:
Private Sub SaveToFile(data As Image, filePath As String)
data.Save(filePath, data.RawFormat)
End Sub
The code to call the method is basically as before, with the exception that an image object needs to be disposed when you're done with it:
Dim data = My.Resources.PICTURE
Dim folderPath = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim fileName = "SAMPLE.EXE"
Dim filePath = Path.Combine(folderPath, fileName)
SaveToFile(data, filePath)
data.Dispose()
The proper way to create and dispose an object in a narrow scope like this is with a Using block:
Dim folderPath = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim fileName = "SAMPLE.EXE"
Dim filePath = Path.Combine(folderPath, fileName)
Using data = My.Resources.PICTURE
SaveToFile(data, filePath)
End Using
Now it is up to you to carry out the same steps for an ICO file. If you are a hands on learner then get your hands on.

WebClient.DownloadFile convert to File VB.NET

Does anyone know how to parse a Webclient.DowloadFile to File in VB.Net?
I'm currently using the following Code but I keep getting the errors:
(BC30491) Expression does not produce a value.
(BC30311) Value of Type can not be converted to File
Private Function DepartmentDataDownloader() As String
Dim webClient As New System.Net.WebClient
'I get here the error BC30491
Dim result As File = webClient.DownloadFile("https://intern.hethoutsemeer.nl/index2.php?option=com_webservices&controller=csv&method=hours.board.fetch&key=F2mKaXYGzbjMA4V&element=departments", "intern.hethoutsemeer.nl.1505213278-Departments.csv")
If webClient IsNot Nothing Then
'and here BC30311
Dim result As File = webClient
UploaderFromDownload(webClient)
End If
Return ""
End Function
The DownloadFile method doesn't return a value, because DownloadFile is a Sub. This is the reason why you get the BC30491 error. The second parameter specifies the path of the local file (and the result of the download).
So you can try something like the following:
Dim webClient As New System.Net.WebClient
'after this the file specified on second parameter should exists.
webClient.DownloadFile("https://intern.hethoutsemeer.nl/index2.php?option=com_webservices&controller=csv&method=hours.board.fetch&key=F2mKaXYGzbjMA4V&element=departments", "intern.hethoutsemeer.nl.1505213278-Departments.csv")
If webClient IsNot Nothing Then
'do something with the downloaded file (File.OpenRead(), File.*).
'Dim result As File
UploaderFromDownload(webClient)
End If
You also try to assign the WebClient value to a File variable. This is not possible so you get the BC30311 error.
Hint: You can't create an instance of the File class. The File class provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects.
source: https://learn.microsoft.com/en-us/dotnet/api/system.io.file

Get *only* file path of files without extension [vb.net]

I'm using a function to get the file paths in my executable path with the extension txt.
Dim FileEntries as string() = _
Directory.GetFiles(Path.GetDirectoryName(Application.ExecutablePath), "*txt"
But now i figures out that it would be better to use this files without the txt extension, despite the fact i can use notepad to change the lines anyway.
How do i use this function to get only the files without the extension?
If i use only "*" it gets all the files, apart from the extension. Thank you!
-EDIT-
I want to avoid any file that it's not suppose to be in the path. I want to gather only the files that have no extension, and therefore avoid any other file. If somehow a file is created there, with any extension, i want to avoid it.
You can use LINQ:
Dim nonTxtFiles =
From fn In Directory.EnumerateFiles(Path.GetDirectoryName(Application.ExecutablePath))
Where Not String.Equals(Path.GetExtension(fn), ".txt", Stringcomparison.InvariantCultureIgnoreCase)
Dim FileEntries as string() = nonTxtFiles.ToArray()
If you only want files without extensions(you have edited your question), it's easy:
Dim noExtFiles = From fn In Directory.EnumerateFiles(path)
Where String.IsNullOrEmpty(IO.Path.GetExtension(fn))
Another solution with Linq is to use the Path.GetExtension() method to see if the file has an extension:
Sub Main
Dim files = getFilenamesWithNoExtension("C:\SomeFolder")
End Sub
Private Function getFilenamesWithNoExtension(foldertosearch As String) As String()
Dim result As String()
result = Directory.EnumerateFiles(foldertosearch).Where(Function(f) String.IsNullOrEmpty(Path.GetExtension(f))).ToArray()
Return result
End Function

vb check for specific file type in dir and perform code

I'm trying to make a program that checks for specific file type in a directory, then executes a code if there are any files of that type found.
I'm assuming something like this:
For Each foundFile As String In
My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
(If any found files are, for example, "txt" files, then display their content.)
Next
Thanks in advance.
You can use Directory.GetFiles or Directory.EnumerateFiles with a parameter for the extension-filter:
Dim directoryPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim allTxtFiles = Directory.EnumerateFiles(directoryPath, ".txt")
For each file As String In allTxtFiles
Console.WriteLine(file)
Next
The difference between both methods is that the first returns a String(), so loads all into memory immediately whereas the second returns a "query". If you want to use LINQ it's better to use EnumerateFiles, f.e. if you want to take the first 10 files:
Dim firstTenFiles As List(Of String) = allTxtFiles.Take(10).ToList()
Dim di As DirectoryInfo = New DirectoryInfo(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
For Each fi In di.GetFiles("*.txt")
Dim content As String = My.Computer.FileSystem.ReadAllText(fi.FullName)
Console.WriteLine(fi.Name)
Next

trying to read a delimited text file from resources - but it wont run

I'm having a problem where instead of reading a text file from the location string, I changed it to read the text file from the resource location and it breaks my program. I've also used the insert snippet method to get most of this code, so it is safe to say I don't know what is going on. Could some one please help?
'reads the text out of a delimited text file and puts the words and hints into to separate arrays
' this works and made the program run
' Dim filename As String = Application.StartupPath + "\ProggramingList.txt"
'this dosnt work and brings back a Illegal characters in path error.
dim filename as string = My.Resources.ProggramingList
Dim fields As String()
'my text files are delimited
Dim delimiter As String = ","
Using parser As New TextFieldParser(filename)
parser.SetDelimiters(delimiter)
While Not parser.EndOfData
' Read in the fields for the current line
fields = parser.ReadFields()
' Add code here to use data in fields variable.
'put the result into two arrays (the fields are the arrays im talking about). one holds the words, and one holds the corresponding hint
Programingwords(counter) = Strings.UCase(fields(0))
counter += 1
'this is where the hint is at
Programingwords(counter) = (fields(1))
counter += 1
End While
End Using
the error
ex.ToString()
"System.ArgumentException: Illegal characters in path.
at System.IO.Path.CheckInvalidPathChars(String path)
at System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)
at System.IO.Path.NormalizePath(String path, Boolean fullCheck)
at System.IO.Path.GetFullPathInternal(String path)
at System.IO.Path.GetFullPath(String path)
at Microsoft.VisualBasic.FileIO.FileSystem.NormalizePath(String Path)
at Microsoft.VisualBasic.FileIO.TextFieldParser.ValidatePath(String path)
at Microsoft.VisualBasic.FileIO.TextFieldParser.InitializeFromPath(String path, Encoding defaultEncoding, Boolean detectEncoding)
at Microsoft.VisualBasic.FileIO.TextFieldParser..ctor(String path)
at HangMan.Form1.GetWords() in I:\vb\HangMan\HangMan\Form1.vb:line 274" String
The TextFieldParser constructor you use expects the name of a file. Instead, it gets the contents of the file. That goes Kaboom, the file content is not a valid path to a file. You'll need to the constructor that takes a Stream and use the StringReader class to provide the stream. For example:
Dim fields As String()
Dim delimiter As String = ","
Dim fileContent As String = My.Resources.ProggramingList
Dim stringStream as New System.IO.StringReader(fileContent)
Using parser As New TextFieldParser(stringStream)
REM etc...
End Using
This is a bit wasteful of memory but not an issue if the text is less than a megabyte or so. If it is more then you shouldn't put it in a resource.
When you debug this code, what is the value of the variable filename after you read it from My.Resources.GamesList? Is it a valid string, does it point to you're file?