Check if part of file name exists

So, I know in the following code example, it checks if a file exists (full file name) ...

If My.Computer.FileSystem.FileExists("C:\Temp\Test.cfg") Then MsgBox("File found.") Else MsgBox("File not found.") End If 

... But what about if a part of the file exists? There is no standard naming convention for files, but they will always have a .cfg extension.

So, I want to check if C: \ Temp contains a * .cfg file, and if it exists, do something, and do something else.

+4
source share
3 answers

* char can be used to define simple filtering patterns. For example, if you use *abc* , it will search for files with a name containing "abc" in them.

 Dim paths() As String = IO.Directory.GetFiles("C:\Temp\", "*.cfg") If paths.Length > 0 Then 'if at least one file is found do something 'do something End If 
+11
source

You can use a wildcard FileSystem.Dir to check if the file matches.

From MSDN

 Dim MyFile, MyPath, MyName As String ' Returns "WIN.INI" if it exists. MyFile = Dir("C:\WINDOWS\WIN.INI") ' Returns filename with specified extension. If more than one *.INI ' file exists, the first file found is returned. MyFile = Dir("C:\WINDOWS\*.INI") ' Call Dir again without arguments to return the next *.INI file in the ' same directory. MyFile = Dir() ' Return first *.TXT file, including files with a set hidden attribute. MyFile = Dir("*.TXT", vbHidden) ' Display the names in C:\ that represent directories. MyPath = "c:\" ' Set the path. MyName = Dir(MyPath, vbDirectory) ' Retrieve the first entry. Do While MyName <> "" ' Start the loop. ' Use bitwise comparison to make sure MyName is a directory. If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then ' Display entry only if it a directory. MsgBox(MyName) End If MyName = Dir() ' Get next entry. Loop 
+1
source

You can use Path.GetExtension from System.IO to get the extension and test it if you are looking for ".cfg". Path.GetExtension returns an empty string if there is no extension.

From MSDN

0
source

All Articles