如何枚举目录时可以访问系统文件夹? [英] How to get access to system folders when enumerating directories?

查看:176
本文介绍了如何枚举目录时可以访问系统文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这code:

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

我得到这个错误:

I get this error:

UnauthorizedAccessException了未处理

访问路径。D:\的System Volume Information \'被拒绝

Access to the path 'D:\System Volume Information\' is denied.

我会如何解决这个问题?

How might I solve this?

推荐答案

有没有办法在.NET中重写您运行此code作为用户的特权。

There is no way in .NET to override privileges of the user you are running this code as.

这里只有1选项真的。确保只有管理员运行此code,或者您在管理员帐户运行它。 明智的做法是,你要么把尝试捕获块和处理这个异常或 运行$ C $之前c您检查该用户是管理员:

There's only 1 option really. Make sure only admin runs this code or you run it under admin account. It is advisable that you either put "try catch" block and handle this exception or before you run the code you check that the user is an administrator:

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);
}
}

这篇关于如何枚举目录时可以访问系统文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆