1

大家好,我一直在尝试在指定目录和所有子目录中搜索具有指定文件扩展名的所有文件。但是,内置命令是无用的,因为如果您无权访问目录,它会出错并死掉。所以这就是我目前所拥有的:

 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

但是我得到一个“System.NullReferenceException:对象引用未设置为对象的实例。” 当我尝试访问存储在 filelist 字符串数组中的数据时。

关于我做错了什么有什么想法吗?

4

2 回答 2

3

您没有实例化Dim filelist() As String数组。尝试di.GetFiles(searchPattern)

Dim files() as FileInfo = di.GetFiles(searchPattern)

使用返回数组字符串的静态方法 Directory.GetFiles

Dim files =  Directory.GetFiles(Path,searchPattern,searchOption)

演示:

 Dim files() As String
 files = Directory.GetFiles(path, "*.exe", SearchOption.TopDirectoryOnly)
 For Each FileName As String In files
     Console.WriteLine(FileName)
 Next

递归目录遍历:

   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
于 2011-12-30T05:50:19.793 回答
1

使用 System.IO.Directory.EnumerateFiles 方法并传入 SearchOption.AllDirectories 以使用特定的搜索模式遍历树。这是一个例子:

foreach (var e in Directory.EnumerateFiles("C:\\windows", "*.dll", SearchOption.AllDirectories))
{
    Console.WriteLine(e);
}
于 2011-12-30T05:50:42.140 回答