枚举目录时如何访问系统文件夹

本文关键字:访问 系统文件夹 何访问 枚举 | 更新日期: 2023-09-27 18:09:37

我正在使用这个代码:

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

我得到这个错误:

UnauthorizedAccessException was unhandled

拒绝访问路径"D:'系统卷信息'"。

我该如何解决这个问题?

枚举目录时如何访问系统文件夹

在。net中没有办法覆盖运行此代码的用户的权限。

其实只有一个选择。确保只有admin运行此代码,或者在admin帐户下运行。建议您放置"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);
}
}

尝试调用此方法,在调用之前再放置一个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);
            }
        }
    }
}

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

// 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.
    }
}