How to find or get files in Directory with Specific word in the file name Visual Basic.net? - vb.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

Related

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

Get only those files in a directory whose name does not start with a certain string

I currently have this code:
Dim FolderInfo As IO.DirectoryInfo = New IO.DirectoryInfo("C:\Scratch")
For Each FInfo As IO.FileInfo In FolderInfo.GetFiles("*.xlsx")
MessageBox.Show(FInfo.ToString())
Next FInfo
Obviously this will get all the files that match the pattern "*.xlsx" - but I am NOT interested in any files that start with "old" - so of course within the For Next, I could do something like if If Not FInfo.Name.StartsWith("old") Then ... and do what I need to do, but I was wondering if there is any way to tell the GetFiles to only get files that "don't start with "old" and end in *.xlsx" ?
I've seen examples in C# that I believe use LINQ - so after the GetFiles there is stuff like ".Where(f => !(f.FullName.StartsWith("old")))" but not sure what ( if there is one ) the equivilant would be for VB.NET ?
Cheers,
Chris.
The syntax is a bit more verbose, but Where works as well in VB
For Each FInfo As IO.FileInfo In FolderInfo.GetFiles("*.xlsx").
Where(Function(x) Not x.Name.StartsWith("old"))
MessageBox.Show(FInfo.ToString())
Next FInfo
I would also add a StringComparison.CurrentCultureIgnoreCase to remove also files that starts with "Old" or "OLD" and so on
For Each FInfo As IO.FileInfo In FolderInfo.GetFiles("*.xlsx").
Where(Function(x) Not x.Name.StartsWith("old", StringComparisong.CurrentCultureIgnoreCase))
MessageBox.Show(FInfo.ToString())
Next FInfo
By the way, you should use the property Name instead of FullName. FullName returns also the path to the file and, obviously, this path doesn't start with "old".
Dim folder As String = "C:\Scratch"
Dim files = Directory.EnumerateFiles(folder, "*.xlsx", SearchOption.TopDirectoryOnly) _
.Where(Function(f) Not Path.GetFileName(f).ToLowerInvariant().StartsWith("old"))
For Each file As string In files
MessageBox.Show(file)
Next file

In vb.net, how do I use directory info with specific files name in the query

Lets say I have a list of files separated by a comma.
Dim listOfFiles As String() = filesPosted.Split(",")
And I use DirectoryInfo to grab that list of files and send it to another array.
Dim files = New DirectoryInfo(StorageRoot) _
.GetFiles("*", SearchOption.TopDirectoryOnly) _
.Where(Function(f) Not f.Attributes.HasFlag(FileAttributes.Hidden)) _
.Where(Function(f) filesPosted.Contains(f.Name)) _
.[Select](Function(f) New FilesStatus(f)).ToArray()
The problem I'm facing is, I need my condition to be more strict. I'll explain:
If my listOfFiles contains ( abc.txt, xyz.txt ) and there's a filename of aabc.txt in the directory that is being searched, it'll return both abc.txt and aabc.txt. I know this is because of this part of the clause:
.Where(Function(f) filesPosted.Contains(f.Name))
As the contains attribute is finding this other file... But I don't want it. I want the files to match exactly based on the string().
Is there a better way to do this without cycling through each file? A tighter way to make it a strict condition on "Contains" ?
Thank you for your help!
Try:
Dim listOfFiles As String() = filesPosted.Split(",").Select(function(f) f.ToLower())
' then
Dim files = New DirectoryInfo(StorageRoot) _
.GetFiles("*", SearchOption.TopDirectoryOnly) _
.Where(Function(f) Not f.Attributes.HasFlag(FileAttributes.Hidden)) _
.Where(Function(f) listOfFiles.Any(function(l) l = f.Name.ToLower())) _
.[Select](Function(f) New FilesStatus(f)).ToArray()
Sorry, poor C# to VB.Net conversion

How to get the file name of a file in VB?

I make a search program for searching a list of files in a computer and then copy the file into a store folder. The file name could be "*11*2.txt" As long as the program find this pattern, it should copy to the store folder. The problem is that I don't know the exactly name of the file before the search and I don't want to rename the file, I don't know how to save the file. Please help
I use the following to find the file, which does its work
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
Dim To_Path As String
To_Path = Form1.TextBox5.Text
For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
Copy2Local(foundFile, To_Path)
Next
End Sub
Here is the current version of the Copy2Local (Note: it is not working right)
Public Sub Copy2Local(ByVal Copy_From_Path As String, ByVal Copy_To_Path As String)
' Specify the directories you want to manipulate.
Try
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
' Copy the file.
File.Copy(Copy_From_Path, Copy_To_Path)
Catch
End Try
End Sub
First, you should check if ToPath is a valid directory since it's coming from a TextBox:
Dim isValidDir = Directory.Exists(ToPath)
Second, you can use Path.Combine to create a path from separate (sub)directories or file-names:
Dim copyToDir = Path.GetDirectoryName(Copy_To_Path)
Dim file = Path.GetFileName(Copy_From_Path)
Dim newPath = Path.Combine(copyToDir, file)
http://msdn.microsoft.com/en-us/library/system.io.path.aspx
(disclaimer: typed from a mobile)
To answer your question: You can get the file name with Path.GetFileName. Example:
Dim fileName As String = Path.GetFileName(foundFile)
However, there's a bunch of other things wrong with your code:
Here,
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
you are overwriting your source file. This does not seem like a good idea. ;-)
And here,
Try
...
Catch
' Do Nothing
End Try
You are throwing away exceptions that would help you find and diagnose problems. Don't do that. It makes debugging a nightmare.
In vb.net, I'm using the following code to find the filename
Textbox1.Text = New FileInfo(OpenFileDialog.FileName).Name
this code work fine with open file dialog box