检查文件名中是否存在一部分内容

5

我知道在下面的代码示例中,它检查文件是否存在(完整文件名)...

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

如果一个文件的一部分存在怎么办?这些文件没有标准命名约定,但它们始终具有 .cfg 扩展名。

因此,我想检查 C:\Temp 是否包含 *.cfg 文件,如果存在,则执行某些操作,否则执行其他操作。


使用FileSystem.Dir获取目录中的文件列表,然后您可以查看任何文件名是否包含您要查找的字符串。 - DeanOC
3个回答

14

*字符可用于定义简单的过滤模式。例如,如果您使用*abc*,它将查找文件名中包含“abc”的文件。

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

1
你可以使用带通配符的 FileSystem.Dir 来查看是否有文件匹配。
来自 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

1
你可以使用System.IO中的Path.GetExtension来获取扩展名并测试是否为你所寻找的".cfg"。如果没有扩展名,Path.GetExtension将返回一个空字符串。
来自MSDN

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接