Search code examples
vb.netfile-exists

Check If A Portion Of A Filename Exists


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.


Solution

  • 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