Prevent Directory.GetFiles() from searching short file names - vb.net

Let's say I have a directory 'C:\Test' with three files in it:
A23456789.txt
A1.txt
G 5.txt
And I run this command:
Dim FileArr = Directory.GetFiles("C:\Test", "*1.txt", SearchOption.AllDirectories)
All three files are returned.
I understand that this is by design and .NET searches the 8.3 short file names as well.
But is there any way to override this and search the actual file names only?
Surely, in this day and age there must be a function to do this. Or do I have to write my own?
I would like the search function to have the same behavior as the Windows Explorer for consistency.

I think the best approach would be to remove the filter from GetFiles and filter it out with LINQ, where you have a little more control:
Dim FileArr = Directory.GetFiles("C:\Test", "*.txt", SearchOption.AllDirectories)
Dim filtered = From f In FileArr Where Path.GetFileName(f).EndsWith("1.txt")
Or some equivalent.

This uses LINQ:
Dim FileArr = IO.Directory.GetFiles("C:\Test", "*.txt", SearchOption.AllDirectories). _
Where(Function(s) s Like "*1.txt")

Related

VB: Search files in a folder and show only Word and PDF files

I have problem searching folder and find all files with specific name.
With this method I am able to browse my folder and find all files. But only Word files.
Dim fi As FileInfo() = path.GetFiles(fileName & "*.doc*", SearchOption.AllDirectories)
Now I would like to search Word and PDF. Is there a way how I can find it?
If I just write a dot instead of .doc it searches the folder but finds all files. Excel, txt etc.
Dim fi As FileInfo() = path.GetFiles(fileName & "*.*", SearchOption.AllDirectories)
The goal would be to find only certain types of files.
It is not possible to use the GetFiles method to enumerate files with multiple extensions. To do that, you'll have to write your own code to do the filtering. I also recommend you use the EnumerateFiles method as it provides better performance over the GetFiles method in most cases.
Here is sample code to do the filtering as you require
Dim filterExtensions = {".docx", ".pdf"}
Dim files = From f In System.IO.Directory.EnumerateFiles("C:\Path", "*.*", _
SearchOption.AllDirectories)
Let fi = New FileInfo(f)
Where filterExtensions.Contains(fi.Extension.ToLower())
Select fi

unable to sort the files getting from system in visual basic

I am trying to get files from system in my application. But when retrieving files it used to come but not in sorted order. I want all my files to come in sorted order. I am very new to this visual basic and i have tried so many things but unable to get files in sorted order. Please Help me out, thanks in advance.
Here is my code : -
Dim path As String = "C:/UTRelOFA/Reva Test/src/00000178"
Dim oFolder As New DirectoryInfo(path)
Dim arr = oFolder.GetFiles(".tif")
Array.Sort(arr)
Cosole.writeline(arr)
I have used so many things and refered this link :
Sorting Directory.GetFiles()
The question here is whether you should be calling DirectoryInfo.GetFiles or Directory.GetFiles. If you call the former then you get a FileInfo array, so if you want to sort by file name then you have to specify that explicitly, e.g.
Dim folderPath = "C:\UTRelOFA\Reva Test\src\00000178"
Dim folder As New DirectoryInfo(folderPath)
Dim files = folder.GetFiles("*.tif")
Array.Sort(files, Function(fi1, fi2) fi1.Name.CompareTo(fi2.Name))
If you don't actually need FileInfo objects but rather just the file paths, don;t use a DirectoryInfo, e.g.
Dim folderPath = "C:\UTRelOFA\Reva Test\src\00000178"
Dim filePaths = Directory.GetFiles(folderPath, "*.tif")
Array.Sort(filePaths)

How to get a filename without using for next

Using VB.Net
Get a file name without using for next from the directory
Dim filefound = Directory.GetFiles("C:\", "1.txt")
For Each inwardfile In filefound
Dim strFilename As String = Path.GetFileName(inwardfile)
Next
The above code is working fine, but i dont want to use for loop because i will always get one file at a time not the list of files also i am searching with filename not like "*.txt"
So How to modify the code, Any one can assist.
Your question is inconsistent which makes it very unclear. Do you want a file name or a collection of them? If you want filename not like "*.txt" then why use "1.txt" for GetFiles?
This will answer the title question How to get a filename without using for next. For this, assume a directory full of ".json" files. Some are named cs###.json (e.g. cs001.json) some are named vb###.json and many others.
Path would work to allow you to examine parts of the filename, but DirectoryInfo will provide access to some of that info via FileInfo objects. This uses EnumerateFiles to be able to filter out unwanted files so they are not even returned to your code/array variable.
Dim dix As New DirectoryInfo("C:\Temp\Json")
Get the json files which DO NOT start with CS. This will return an array of FileInfo objects in case you need to do further exclusions:
Dim jFile = dix.EnumerateFiles.Where(Function(f) f.Extension = ".json" AndAlso
f.Name.StartsWith("cs") = False).
ToArray()
Get the json files which ARE "*1.json" and DO NOT start with "cs". In this case, the last Select method will cause an array of filenames to be returned:
Dim jFile = dix.EnumerateFiles.Where(Function(f) f.Extension = ".json" AndAlso
f.Name.EndsWith("1.json") AndAlso
f.Name.StartsWith("cs") = False).
Select(Function(q) q.Name).
ToArray()
Change the Select to 'Function(q) q.FullName` if you want the full path name. These should come close to whatever you are really looking for.

Search multiple files though sub folders VB.net

I'm having a hard time trying to figure it out how to find multiple files through sub folders, I'm looking for different file names and I think that's why I can't solve it.
"file_name" in the code is the name of the varible, I pull the name of the document from the data base which it's stored in a field without the extension and then when it finds the .docx/doc file it should convert it to pdf.
Dim di As DirectoryInfo = New DirectoryInfo("\\192.168.1.70\sisint\court\
agreements")
For Each fi In di.GetFiles(file_name, SearchOption.AllDirectories)
'seleccionamos los archivos con las extensiones de Word
If fi.Extension.ToUpper = ".DOC" Or fi.Extension.ToUpper = ".DOCX" Then
ListaArchivos.Add(fi.FullName)
ListaNombres.Add((fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length)))
End If
Next
To search a directory with multiple sub directories for a file you can use the following line of code:
Dim folders As List(Of String) = New DirectoryInfo("C:\Test").EnumerateFiles("test.txt", SearchOption.AllDirectories).[Select](Function(d) d.FullName).ToList()
Replace "C:\Test" with the directory to search and "test.txt" with the filename to search for. If the same file name is in multiple directories all iles matching that name will be returned.
To find multiple file names, just loop through your list(file_name) replacing "test.txt" with the file. How you save all the output is up to you. You can add everything found to 1 large list and then convert them all to pdf's, or you can convert them as you find them.
Here is an example:
Private Function FindFiles() As List(Of String)
Dim allFilesFound As New List(Of String)
Dim dirSearch = "C:\Test"
Dim file_name As New List(Of String) From {"test.txt", "test2.txt"}
For Each file In file_name
allFilesFound.AddRange(New DirectoryInfo(dirSearch).EnumerateFiles(file, SearchOption.AllDirectories).[Select](Function(d) d.FullName).ToList())
Next
Return allFilesFound
End Function
Keep in mind that the more files in file_name and the farther up the Directory tree you start searching from, the longer this will take. If you are dealing with large amounts of files, then consider using recursion so you can find all files in one pass. You can take a look here Recursively search folder with subdirectories in .NET and modify the code demonstrated there to fit your search pattern.

.NET find .xls or.xlsx file with GetFiles using wildcard? example: .xls*

I need to find an Excel file. However, the extension of the file I"m looking for could be .xls or .xlsx. I was considering using FileExists but I can't use a wildcard with that. Here's my attempt at using GetFiles, however, the .xls* part of my code does not work. I've never used GetFiles before, can anyone give me some guidance on what I'm doing wrong?
Dim InputFormPath As String = "W:\TOM\ERIC\NET Dev\"
Dim wbNameXLSInputForm As String = StatVar.xlApp.Sheets("New Calculator Input").Range("D15").Text & ".xls*"
Dim XLSInputForm As String = wbNameXLSInputForm
Dim dirs As String() = Directory.GetFiles(InputFormPath, wbNameXLSInputForm)
If dirs.Length <> 0 Then
'do something
End If
Take a look at this documentation. It says: The following list shows the behavior of different lengths for the searchPattern parameter: "*.abc" returns files having an extension of.abc,.abcd,.abcde,.abcdef, and so on.