我正在尝试让应用程序查看文件是否包含文本的一部分。如果确实包含它,我需要将它放在一个字符串中(和/或显示它)。
到目前为止,我有它的工作,只要说它是否被发现,但我不确定如何将结果转换为字符串。
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
当我尝试添加类似Dim FileName as string = file
的内容时,我会
类型1维数组的值无法转换错误
或者,当我将Dim file As String()
更改为Dim file As String
时,我收到同样的错误。
答案 0 :(得分:5)
file
是所有找到文件的绝对路径的数组。您必须使用例如For Each
loop迭代它。
为了便于阅读,我建议您将其重命名为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
以上将输出:
File: C:\test\1234_a.txt
Name: 1234_a.txt
...进入控制台。
如果您只想访问第一场比赛,您可以这样做:
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