Check If A Portion Of A Filename Exists

Muhnamana picture Muhnamana · Feb 4, 2013 · Viewed 11.5k times · Source

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

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

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

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

Answer

theGD picture theGD · Feb 4, 2013

The * char can be used to define simple patterns of filtering. For example, if you use *abc* it will look for the files thats name contains "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