0

我正在使用这段代码:

DirectoryInfo dir = new DirectoryInfo("D:\\");
foreach (FileInfo file in dir.GetFiles("*.*",SearchOption.AllDirectories))
{
    MessageBox.Show(file.FullName);
}

我收到此错误:

UnauthorizedAccessException 未处理

拒绝访问路径“D:\System Volume Information\”。

我该如何解决这个问题?

4

3 回答 3

1

尝试调用此方法,在调用之前再放一个 try catch 块 - 这意味着顶层文件夹缺少必需的授权:

     static void RecursiveGetFiles(string path)
    {
        DirectoryInfo dir = new DirectoryInfo(path);
        try
        {

            foreach (FileInfo file in dir.GetFiles())
            {
                MessageBox.Show(file.FullName);
            }
        }
        catch (UnauthorizedAccessException)
        {

            Console.WriteLine("Access denied to folder: " + path);
        }

        foreach (DirectoryInfo lowerDir in dir.GetDirectories())
        {
            try
            {
                RecursiveGetFiles(lowerDir.FullName);

            }
            catch (UnauthorizedAccessException)
            {

                MessageBox.Show("Access denied to folder: " + path);
            }
        }
    }

}
于 2011-09-24T19:44:31.637 回答
1

.NET 中无法覆盖运行此代码的用户的权限。

真的只有1个选项。确保只有管理员运行此代码,或者您在管理员帐户下运行它。建议您放置“try catch”块并处理此异常,或者在运行代码之前检查用户是否为管理员:

WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity);
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
DirectoryInfo dir = new DirectoryInfo("D:\\");
foreach (FileInfo file in dir.GetFiles("*.*",SearchOption.AllDirectories))
{
MessageBox.Show(file.FullName);
}
}
于 2011-09-24T19:07:03.810 回答
0

您可以手动搜索文件树而忽略系统目录。

// Create a stack of the directories to be processed.
Stack<DirectoryInfo> dirstack = new Stack<DirectoryInfo>();
// Add your initial directory to the stack.
dirstack.Push(new DirectoryInfo(@"D:\");

// While there are directories on the stack to be processed...
while (dirstack.Count > 0)
{
    // Set the current directory and remove it from the stack.
    DirectoryInfo current = dirstack.Pop();

    // Get all the directories in the current directory.
    foreach (DirectoryInfo d in current.GetDirectories())
    {
        // Only add a directory to the stack if it is not a system directory.
        if ((d.Attributes & FileAttributes.System) != FileAttributes.System)
        {
            dirstack.Push(d);
        }
    }

    // Get all the files in the current directory.
    foreach (FileInfo f in current.GetFiles())
    {
        // Do whatever you want with the files here.
    }
}
于 2012-08-24T20:28:32.127 回答