Reputation:
I need to search a directory with sub folders for one specific file and get that file's directory path. All the examples I've found has been to search for a file type and place those files in a list.The code I have returns a count of 1, but not the file name and path. What is the best way to achieve this?
Code
Dim folders As List(Of String) = New DirectoryInfo(imgLocation).EnumerateFiles(graphicName, SearchOption.AllDirectories).[Select](Function(d) d.FullName).ToList()
For Each file In folders
Debug.Write("file found " & file & vbCr)
Next
Upvotes: 0
Views: 771
Reputation: 2705
In order to get information about files you need to use FileInfo class like the example below shows:
Sub SearchFiles()
Dim files() As String = IO.Directory.GetFiles("your directory root path here", "*.xml", SearchOption.AllDirectories)
For Each cFile In files
Dim fi As FileInfo = New IO.FileInfo(cFile)
Console.WriteLine("File name : " & fi.Name & " is in directory " & fi.Directory.Name & " or full path directory: " & fi.DirectoryName)
Next
End Sub
And for a single file use this:
Sub SearchSingleFile()
Dim ext As String = ".xml"
Dim files As List(Of String) = IO.Directory.GetFiles("put your directory here", "*" & ext, SearchOption.AllDirectories).Where(Function(fname) fname.ToLower.EndsWith("your filename here" & ext)).ToList
If files IsNot Nothing AndAlso files.Count > 0 Then
Dim fInfo As IO.FileInfo = New IO.FileInfo(files(0))
Console.WriteLine("File name : " & fInfo.Name & " is in directory " & fInfo.Directory.Name & " or full path directory: " & fInfo.DirectoryName)
End If
End Sub
put your directory path and change extension *.xml
in your extension
Upvotes: 0
Reputation:
If you just want to find a specific file, you could:
Dim file As String = IO.Directory.EnumerateFiles("SearchDir",
"TheTargetFileName",
IO.SearchOption.AllDirectories).FirstOrDefault
Then you can get it's directory:
If file IsNot Nothing Then
Dim dir As String = IO.Path.GetDirectoryName(file)
'...
End If
Upvotes: 1