如何正确枚举所选路径中的文件?

时间:2012-04-04 11:37:49

标签: vb.net file-io iteration

Visual Studio 2008(vb.net) 我做了简单的病毒,但当我用这段代码进行全面扫描时:

FolderBrowserDialog1.SelectedPath = ("C:\")
    'first scan:************************************
    Try

        For Each strDir As String In
        System.IO.Directory.GetDirectories(FolderBrowserDialog1.SelectedPath)

            For Each strFile As String In System.IO.Directory.GetFiles(strDir)

                ListBox1.Items.Add(strFile)

            Next
        Next

        'Start the timer:

    Catch ex As Exception
    End Try

    Timer1.Start()`

只扫描前6个文件...... 我认为来自Windows文件夹权限的问题(Windows - 程序文件...等) 那么如何解决呢?

2 个答案:

答案 0 :(得分:2)

在catch块中放置Console.WriteLine(ex),以便可以看到引发的任何异常。你可能会看到你的问题。最有可能是权限。

答案 1 :(得分:1)

您可以尝试以下方法:

For Each strFile As String In System.IO.Directory.GetFiles(strDir, "*", IO.SearchOption.AllDirectories)

修改

您可以尝试在此主题中找到的最后一个解决方案: http://www.vbforums.com/showthread.php?t=624969

我自己尝试了这个并且速度非常慢,但工作正常。

Public Class Form1

    Private Sub foo(ByVal aDir As String)
        Try

            Dim di As New IO.DirectoryInfo(aDir)
            Dim aryFiles() As IO.FileInfo = di.GetFiles("*.*")
            Dim aryDirs() As IO.DirectoryInfo = di.GetDirectories()

            For Each fi As IO.FileInfo In aryFiles
                rslts.Add(fi.FullName)
            Next

            For Each d As IO.DirectoryInfo In aryDirs
                foo(d.FullName)
            Next

        Catch ex As Exception
            'Stop 'the catch should be more specific
        End Try

    End Sub

    Dim rslts As List(Of String)

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        rslts = New List(Of String)
        foo("C:\")
        ListBox1.Items.Clear()
        ListBox1.Items.AddRange(rslts.ToArray)
     End Sub
End Class

看起来你的解决方案基本上遍历它可以找到的第一个文件夹并停在那里。此解决方案略有不同,因为它将根据起始位置递归浏览所有文件和文件夹。