按文件扩展名搜索 VB.NET
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8676516/
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
Searching By File Extensions VB.NET
提问by crackruckles
Hi all i have been trying to search a specified directory and all sub directories for all files that have the specified file extension. However the inbuilt command is useless as it errors up and dies if you dont have access to a directory. So here's what i have at the moment:
大家好我一直在尝试搜索具有指定文件扩展名的所有文件的指定目录和所有子目录。但是,内置命令是无用的,因为如果您无权访问目录,它会出错并死亡。所以这就是我目前所拥有的:
Private Function dirSearch(ByVal path As String, Optional ByVal searchpattern As String = ".exe") As String()
Dim di As New DirectoryInfo(path)
Dim fi As FileInfo
Dim filelist() As String
Dim i As Integer = 0
For Each fi In di.GetFiles
If System.IO.Path.GetExtension(fi.FullName).ToLower = searchpattern Then
filelist(i) = fi.FullName
i += 1
End If
Next
Return filelist
End Function
However i get an "System.NullReferenceException: Object reference not set to an instance of an object." when i try to access the data stored inside the filelist string array.
但是,我收到“System.NullReferenceException:未将对象引用设置为对象的实例”。当我尝试访问存储在文件列表字符串数组中的数据时。
Any idea's on what im doing wrong?
关于我做错了什么的任何想法?
回答by adatapost
You didn't instantiate the Dim filelist() As String
array. Try di.GetFiles(searchPattern)
您没有实例化Dim filelist() As String
数组。尝试di.GetFiles(searchPattern)
Dim files() as FileInfo = di.GetFiles(searchPattern)
Use static method Directory.GetFiles that returns an array string
使用返回数组字符串的静态方法 Directory.GetFiles
Dim files = Directory.GetFiles(Path,searchPattern,searchOption)
Demo:
演示:
Dim files() As String
files = Directory.GetFiles(path, "*.exe", SearchOption.TopDirectoryOnly)
For Each FileName As String In files
Console.WriteLine(FileName)
Next
Recursive directory traversal:
递归目录遍历:
Sub Main()
Dim path = "c:\jam"
Dim fileList As New List(Of String)
GetAllAccessibleFiles(path, fileList)
'Convert List<T> to string array if you want
Dim files As String() = fileList.ToArray
For Each s As String In fileList
Console.WriteLine(s)
Next
End Sub
Sub GetAllAccessibleFiles(path As String, filelist As List(Of String))
For Each file As String In Directory.GetFiles(path, "*.*")
filelist.Add(file)
Next
For Each dir As String In Directory.GetDirectories(path)
Try
GetAllAccessibleFiles(dir, filelist)
Catch ex As Exception
End Try
Next
End Sub
回答by doogle
Use System.IO.Directory.EnumerateFiles method and pass SearchOption.AllDirectories in to traverse the tree using a specific search pattern. Here is an example:
使用 System.IO.Directory.EnumerateFiles 方法并传入 SearchOption.AllDirectories 以使用特定搜索模式遍历树。下面是一个例子:
foreach (var e in Directory.EnumerateFiles("C:\windows", "*.dll", SearchOption.AllDirectories))
{
Console.WriteLine(e);
}