枚举目录时如何访问系统文件夹?
我正在使用这段代码:
DirectoryInfo dir = new DirectoryInfo("D:\\");
foreach (FileInfo file in dir.GetFiles("*.*",SearchOption.AllDirectories))
{
MessageBox.Show(file.FullName);
}
我收到此错误:
UnauthorizedAccessException 未处理
对路径“D:\System Volume Information\”的访问被拒绝。
我该如何解决这个问题?
I am using this code:
DirectoryInfo dir = new DirectoryInfo("D:\\");
foreach (FileInfo file in dir.GetFiles("*.*",SearchOption.AllDirectories))
{
MessageBox.Show(file.FullName);
}
I get this error:
UnauthorizedAccessException was unhandled
Access to the path 'D:\System Volume Information\' is denied.
How might I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
缪败2024-12-13 11:05:22
尝试调用此方法,在调用之前再放置一个 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);
}
}
}
}
少年亿悲伤2024-12-13 11:05:22
您可以手动搜索文件树而忽略系统目录。
// 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.
}
}
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
.NET 中无法覆盖您运行此代码的用户的权限。
确实只有 1 个选择。确保只有管理员运行此代码,或者您在管理员帐户下运行它。
建议您放置“try catch”块并处理此异常,或者
在运行代码之前,请检查用户是否是管理员:
There is no way in .NET to override privileges of the user you are running this code as.
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: