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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14693651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:11:16  来源:igfitidea点击:

Check If A Portion Of A Filename Exists

vb.netfile-exists

提问by Muhnamana

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.

...但是如果文件的一部分存在呢?文件没有标准命名约定,但它们将始终具有 .cfg 扩展名。

So I want to check if C:\Temp contains a *.cfg file and if it exists, do something, else do something else.

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

回答by theGD

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.

*炭可以被用来定义滤波简单图案。例如,如果您使用*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

回答by DeanOC

You can use FileSystem.Dir with a wildcard to see if there is a file match.

您可以使用带有通配符的 FileSystem.Dir 来查看是否存在文件匹配。

From MSDN

来自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

回答by TazAstroSpacial

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.

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

From MSDN

来自MSDN