如果文件名包含特定文本,则显示全名

dwb*_*dwb 1 vb.net

我正在尝试让应用程序查看文件是否包含文本的一部分.如果确实包含它,我需要将它放在一个字符串中(和/或显示它).

到目前为止,我有它的工作,只要说它是否被发现,但我不确定如何将结果转换为字符串.

 Dim dir As String = "C:\test\"
    Dim file As String()
    file = IO.Directory.GetFiles(dir, "1234" & "_*")
    If file.Length > 0 Then
        'Found
    Else
        'Not Found
    End If
Run Code Online (Sandbox Code Playgroud)

当我尝试添加像Dim FileName as string = file我得到的东西时

类型1维数组的值无法转换错误

或者当我Dim file As String()改为Dim file As String我时会得到同样的错误.

Vis*_*ent 5

file是所有找到的文件的绝对路径数组.你必须使用例如For Each循环来迭代它.

为了便于阅读,我建议你将其重命名为files.

Dim files As String() = IO.Directory.GetFiles(dir, "1234" & "_*")
For Each file As String In files
    Dim fileName As String = IO.Path.GetFileName(file)

    'Do your stuff here.

    'Logging each file (this is just an example).
    Console.WriteLine("File: " & file)
    Console.WriteLine("Name: " & fileName)
Next
Run Code Online (Sandbox Code Playgroud)

以上将以输出为例:

File: C:\test\1234_a.txt
Name: 1234_a.txt
Run Code Online (Sandbox Code Playgroud)

......进入控制台

如果您只想访问第一场比赛,您可以这样做:

If files.Length > 0 Then
    Dim file As String = files(0) '0 is the first index, 1 is the second, and so on...
    Dim fileName As String = IO.Path.GetFileName(file)

    'Do your stuff here.
End If
Run Code Online (Sandbox Code Playgroud)