【问题标题】:Can't get all files from C:\ directories and subdirectories无法从 C:\ 目录和子目录中获取所有文件
【发布时间】:2015-04-10 21:11:26
【问题描述】:

我正在尝试计算 C:\ 及其子目录中存在的所有文件。 这是我到目前为止尝试过的,但没有成功。该函数始终返回 0。

Private Function CountFiles(ByVal Path As String) As Integer
    Dim D As New DirectoryInfo(Path)
    Dim TotalFiles As Integer = 0
    Try
        For Each DD As DirectoryInfo In D.GetDirectories("*", IO.SearchOption.AllDirectories)
            For Each FF As FileInfo In DD.GetFiles("*", IO.SearchOption.AllDirectories)
                TotalFiles += 1
            Next
        Next
    Catch ex As Exception

    End Try
    Return TotalFiles
End Function

奇怪的是我可以计算包含在另一个目录中的文件(除了 C:\ )。

函数在For Each DD As DirectoryInfo In D.GetDirectories 行之前停止。

谁能帮帮我?提前致谢!

【问题讨论】:

  • C: 盘上的许多文件夹都被操作系统锁定和保护。可能会引发异常,但您没有显示 ex.Message 变量的内容,因此您无法知道那里发生了什么。
  • 是的,你是对的,这就是我得到的:C:\$Recycle.Bin\S-1-5-18 is denied.

标签: vb.net


【解决方案1】:

您需要以管理员身份运行程序才能读取 C 盘中的目录。检查这个answer by Matt

其他选项是转到安全和give full access to usernameEveryone(完全不推荐)

更新:

我在我的系统上尝试了这个,发现没有任何管理员访问权限的解决方法。我通过调试模式发现了目录的一些属性,这些属性是隐藏的、系统的或某些窗口等。使用这些属性,我在我的计算机上得到了这个工作。

  Public Function CountFiles(ByVal Path As String) As Integer
        Dim D As New DirectoryInfo(Path)
        Dim TotalFiles As Integer = 0


        For Each DD As DirectoryInfo In D.GetDirectories()
            Dim attrib = Nothing

            If Not IsNothing(DD) Then
                attrib = DD.Attributes
            End If

'Attributes value below indicate they are system directories and cannot be accessed

            If Not (attrib = 22 Or attrib = 9238 Or IsNothing(attrib)) Then
                For Each FF As FileInfo In DD.GetFiles("*", IO.SearchOption.AllDirectories)
                    On Error Resume Next
                    TotalFiles += 1
                Next
            End If
        Next


        Return TotalFiles
    End Function

【讨论】:

  • 我已经尝试以管理员身份运行它,但还是一样。有没有办法跳过受限目录并继续下一个?
  • @user2921419 我更新了我的答案并添加了一个工作代码。我在我的机器上试了一下,效果很好。我进行了调试并获得了属性并忽略了那些目录。
【解决方案2】:

您没有获得文件计数的原因是因为您的逻辑在 try/catch 块上,并且当发生访问权限异常时循环中断,如果 TotalFiles0 可能是因为第一次尝试读取找到的第一个文件夹失败。

您可以尝试以下我的方法,这只是一种避免访问您无权读取的文件夹的方法。

它使用多核改进。

使用示例

Dim files As IEnumerable(Of FileInfo) = 
    FileDirSearcher.GetFiles("C:\", SearchOption.AllDirectories)

或:

Dim filePaths As IEnumerable(Of String) = 
    FileDirSearcher.GetFilePaths("C:\", SearchOption.AllDirectories)

来源

Filedirsearcher By Elektro

请注意,源公开了各种方法重载,您可以将它们用于其他需求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2014-11-10
    相关资源
    最近更新 更多