Reputation: 1044
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.
Upvotes: 5
Views: 13775
Reputation: 131
You could use Path.GetExtension from System.IO to get the extension and test if it the one you are looking for ".cfg". Path.GetExtension return an empty string if there is no extension.
From MSDN
Upvotes: 1
Reputation: 1069
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
Upvotes: 14
Reputation: 7262
You can use FileSystem.Dir with a wildcard to see if there is a file match.
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's a directory.
MsgBox(MyName)
End If
MyName = Dir() ' Get next entry.
Loop
Upvotes: 1