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

我正在使用此代码:

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

我收到此错误:

UnauthorizedAccessException未处理

对“D:\ System Volume Information”路径的访问被拒绝。

我怎么解决这个问题?

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

真的只有一个选择。 确保只有管理员运行此代码或您在管理员帐户下运行它。 建议您放置“try catch”块并处理此exception,或者在运行代码之前检查用户是否为管理员:

 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块 – 这将意味着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); } } } } 

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

 // Create a stack of the directories to be processed. Stack dirstack = new Stack(); // 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. } }