In vb.net, how do I get files from a directory based on a comma separated string? - vb.net

I need to create an array() from files in a folder. Here's an example of how I would get all files within a folder.
Dim filesList = New DirectoryInfo("MyPath").GetFiles("*", SearchOption.TopDirectoryOnly).Where(Function(f) Not f.Attributes.HasFlag(FileAttributes.Hidden)).[Select](Function(f) New AClassNameHere(f)).ToArray()
I want to do the exact same thing, but only get files that exist in a comma separated string.
Dim myFiles as String = "filename1.jpg,filename2.jpg,filename3.jpg"
Where you see the AClassNameHere is a class I need to send each file to, and it would also be great if I knew how to send additional data about each file, like its type, size, etc.
Thank you kindly!

You could narrow the query results by adding an additional .Where() filter
Dim myFiles as String = "filename1.jpg,filename2.jpg,filename3.jpg"
Dim filesList = New DirectoryInfo("MyPath")
.GetFiles("*", SearchOption.TopDirectoryOnly)
.Where(Function(f) Not f.Attributes.HasFlag(FileAttributes.Hidden))
.Where(Function(f) myFiles.Contains(f.Name))
.[Select](Function(f) New AClassNameHere(f)).ToArray()
A better option would be to ensure that all filenames follow a pattern.
New DirectoryInfo("MyPath").GetFiles("filename*.jpg", SearchOption.TopDirectoryOnly)

Use this...
Dim Files() As String
Files= filesList.Split(",")
For each File In Files
Msgbox(File)
Next

Related

How to keep the content of ListBox in Vb.net

If i want to keep the content of a textbox i do this
TextBox1.Text = TextBox1.Text & Something
Is there a way to do the same thing for the content of Items of a Listbox?
In my RichTextBox3 i have the list of files in the C:\Work directory
I Tried this code but it's giving me The content of the last line (It's not adding the lines before)
Do Until number = RichTextBox3.Lines.Length
Dim directory = "C:\Work\" & RichTextBox3.Lines(number)
Dim files() As System.IO.FileInfo
Dim dirinfo As New System.IO.DirectoryInfo(directory)
files = dirinfo.GetFiles("*", IO.SearchOption.AllDirectories)
For Each file In files
ListBox1.Items.Add(file)
Next
number = number + 1
Loop
Help is appreciated
Thanks to all of you
I'm not sure that this will address your stated problem but there's a serious issue with that code and I need to provide a long code snippet to address it and that won't be readable in a comment.
The Lines property of a TextBox or RichTextBox is not "live" data, i.e. it doesn't refer to an array stored within the object. Each time you get the property, a new array is created. You are getting RichTextBox3.Lines twice for every iteration of that loop, so that's obviously wrong. You also should not be adding items to the ListBox one by one like that. You should be creating a list of all the items first, then adding them all with a single call to AddRange:
Dim files As New List(Of FileInfo)
For Each line In RichTextBox3.Lines
Dim folderPath = Path.Combine("C:\Work", line)
Dim folder As New DirectoryInfo(folderPath)
files.AddRange(folder.GetFiles("*", SearchOption.AllDirectories))
Next
ListBox1.Items.AddRange(files.ToArray())
If that code doesn't work as expected, you can debug it and view the contents of files at various stages to make sure that you are getting the files you expect. It might also be worth testing folder.Exists before calling GetFiles, unless you're absolutely sure that each line in the RichTextBox represents an existing folder.
This will do what you want.
number = 0
ListBox1.items.clear()
Do Until number = RichTextBox3.Lines.Length
Dim directory = "C:\Work\" & RichTextBox3.Lines(number)
Dim files() As System.IO.FileInfo
Dim dirinfo As New System.IO.DirectoryInfo(directory)
files = dirinfo.GetFiles("*", IO.SearchOption.AllDirectories)
For Each file In files
ListBox1.Items.Add(file)
Next
number = number + 1
Loop

replace text multiple file vb.net

I want multiple files with a name and in a different format
I will replace some of the text
To do this, use the following command:
Dim sb As New StringBuilder(File.ReadAllText("tmp\boot_root\initrd\fstab.*"))
sb.Replace("ro,barrier", "ro,noatime,barrier")
sb.Replace("ro,errors", "ro,noatime,errors")
But this does not work. I need a better command to do this
help please
To get a list of all files matching a pattern in a given directory use Directory.Getfiles(path, pattern). Example:
Dim list as String()
Dim path as String = "C:\tmp\"
Dim filename as String = "fstab"
list = Directory.GetFiles(path, filename & ".*")
For Each file As String In list
'Logic goes here.
Next

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

How to find or get files in Directory with Specific word in the file name Visual Basic.net?

I need to get files from a directory containing specific characters in it's name:
The following code below will return any file with the .csv extension. The problem is there are other csv file I need to leave alone or not get.
Dim FileLocation As DirectoryInfo = _
New DirectoryInfo("C:\Folder\Subfolder\Data\Input\")
Dim fi As FileInfo() = FileLocation.GetFiles("*.csv")
Instead of getting any csv file, I would like to get a file with the word data, so any file name containing the word data. Example: *my_data_file.csv*
How do I do this with the code above?
You can update the filter with the string you want to account for (caps will automatically be taken care of):
Dim fi As FileInfo() = FileLocation.GetFiles("*data*.csv")
In any case, bear in mind that this filtering is not "too accurate". For example, the code above would also account for any file (including "data"), whose extension includes csv (e.g., *.csva, *.csvb, etc.). If you want a 100%-reliable approach you should better set up a loop and carry out the filtering "manually"; loops are pretty fast and you wouldn't even notice the difference.
Example of a loop:
Dim fi As List(Of FileInfo) = New List(Of FileInfo)
For Each File In FileLocation.GetFiles()
If (File IsNot Nothing) Then
If (Path.GetExtension(File.ToString.ToLower) = ".csv") Then
If (File.ToString.ToLower.Contains("data")) Then fi.Add(File)
End If
End If
Next
This code will work for sure under your exact requirements and might take care of more complex requests. I have accounted for a List just to show the point clearer.
If you can use LINQ extensions then you can do it this way:
' Get Files {directory} {recursive} {ext} {word in filename}
Private Function Get_Files(ByVal directory As String, _
ByVal recursive As IO.SearchOption, _
ByVal ext As String, _
ByVal with_word_in_filename As String) As List(Of IO.FileInfo)
Return IO.Directory.GetFiles(directory, "*" & If(ext.StartsWith("*"), ext.Substring(1), ext), recursive) _
.Where(Function(o) o.ToLower.Contains(with_word_in_filename.ToLower)) _
.Select(Function(p) New IO.FileInfo(p)).ToList
End Function
Usage example:
For Each file As IO.FileInfo In Get_Files("C:\Folder\Subfolder\Data\Input\", _
IO.SearchOption.TopDirectoryOnly, _
"csv", _
"data")
MsgBox(file.Name)
Next
Replace the wildcard search below "." with your search criteria, for example you want all files that start with name "Hospital*"
Dim Folder As New IO.DirectoryInfo("C:\SampleFolder")
For Each File as IO.FileInfo in Folder.GetFiles("*.*",IO.SearchOption.AllDirectories)
ListBox1.Items.Add(File.FullName)
Next
I would have added this as a comment to the accepted answer, but I do not have enough points to do so:
I just wanted to add varocarbas's answer that, if anyone was wondering (as I was) if this would work in a web scenario as well, it will. Just place the web path inside Server.MapPath() like this:
Dim FileLocation As DirectoryInfo =
New DirectoryInfo(Server.MapPath("/Folder/SubFolder/Data/Input/"))
NOTE: Will NOT work with full url's (no 'http://www.123.com').
Dim Folder As New IO.DirectoryInfo("C:\SampleFolder")
For Each File as IO.FileInfo in Folder.GetFiles("*.*",IO.SearchOption.AllDirectories)
ListBox1.Items.Add(File.FullName)
Application.DoEvents()
Next