我正在使用此代码:
DirectoryInfo dir = new DirectoryInfo("D:\\");
foreach (FileInfo file in dir.GetFiles("*.*",SearchOption.AllDirectories))
{
MessageBox.Show(file.FullName);
}
我收到此错误:
UnauthorizedAccessException未处理
拒绝访问路径'D:\ System Volume Information \'。
我该如何解决这个问题?
答案 0 :(得分:1)
.NET中没有办法覆盖运行此代码的用户的权限。
真的只有一个选项。确保只有管理员运行此代码或您在管理员帐户下运行它。 建议您放置“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);
}
}
答案 1 :(得分:0)
尝试调用此方法在调用之前再添加一个try catch块 - 这将意味着top文件夹缺少必需的授权:
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);
}
}
}
}
答案 2 :(得分: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.
}
}