问题
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?
回答1:
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:
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);
}
}
回答2:
try calling this method putting one more try catch block before calling - this will mean top folder lacks required authorisation:
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);
}
}
}
}
回答3:
You can manually search the file tree ignoring system directories.
// 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.
}
}
来源:https://stackoverflow.com/questions/7541142/how-to-get-access-to-system-folders-when-enumerating-directories