Vb.net 检查文件名的一部分是否存在

Vb.net 检查文件名的一部分是否存在,vb.net,file-exists,Vb.net,File Exists,所以我知道在下面的代码示例中,它会检查文件是否存在(完整文件名) …但若文件的一部分存在呢?文件没有标准的命名约定,但它们的扩展名总是.cfg 因此,我想检查C:\Temp是否包含一个*.cfg文件,如果它存在,那么做一些事情,或者做一些其他事情。字符可以用来定义简单的过滤模式。例如,如果使用*abc*它将查找其名称中包含“abc”的文件 您可以将FileSystem.Dir与通配符一起使用,以查看是否存在文件匹配 从 Dim MyFile、MyPath、MyName作为字符串 '如果存在,则返

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

…但若文件的一部分存在呢?文件没有标准的命名约定,但它们的扩展名总是.cfg


因此,我想检查C:\Temp是否包含一个*.cfg文件,如果它存在,那么做一些事情,或者做一些其他事情。

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


您可以将FileSystem.Dir与通配符一起使用,以查看是否存在文件匹配

Dim MyFile、MyPath、MyName作为字符串
'如果存在,则返回“WIN.INI”。
MyFile=Dir(“C:\WINDOWS\WIN.INI”)
'返回具有指定扩展名的文件名。如果有多个*.INI
'文件存在,将返回找到的第一个文件。
MyFile=Dir(“C:\WINDOWS\*.INI”)
'在不带参数的情况下再次调用Dir以返回
'相同的目录。
MyFile=Dir()
'返回第一个*.TXT文件,包括具有设置隐藏属性的文件。
MyFile=Dir(“*.TXT”,vbHidden)
'在C:\中显示代表目录的名称。
MyPath=“c:\”'设置路径。
MyName=Dir(MyPath,vbDirectory)'检索第一个条目。
在MyName“”启动循环时执行此操作。
'使用位比较确保MyName是目录。
如果(GetAttr(MyPath&MyName)和vbDirectory)=vbDirectory,则
'仅当条目是目录时才显示它。
MsgBox(我的名字)
如果结束
MyName=Dir()'获取下一个条目。
环

您可以使用System.IO中的Path.GetExtension来获取扩展名,并测试它是否是您要查找的“.cfg”扩展名。如果没有扩展名,则Path.GetExtension返回空字符串


中,使用FileSystem.Dir获取目录中文件的列表,然后可以查看是否有任何文件名包含要查找的字符串。
If My.Computer.FileSystem.FileExists("C:\Temp\Test.cfg") Then
   MsgBox("File found.")
Else
   MsgBox("File not found.")
End If
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
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