【问题标题】:Check If A Portion Of A Filename Exists检查文件名的一部分是否存在
【发布时间】:2013-01-19 13:27:08
【问题描述】:

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

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 获取目录中的文件列表,然后您可以查看是否有任何文件名包含您要查找的字符串。

标签: vb.net file-exists


【解决方案1】:

* 字符可用于定义简单的过滤模式。例如,如果您使用*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

【讨论】:

    【解决方案2】:

    您可以使用带通配符的 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
    

    【讨论】:

      【解决方案3】:

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

      来自MSDN

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 2018-11-23
        • 2018-02-03
        • 2022-01-09
        • 1970-01-01
        • 2015-07-24
        • 1970-01-01
        • 2018-11-28
        • 2012-04-18
        相关资源
        最近更新 更多