简体   繁体   English

C#treeview未经授权的异常

[英]C# treeview Unauthorized exception

So I followed MS article http://msdn.microsoft.com/en-us/library/ms171645.aspx 因此,我关注了MS文章http://msdn.microsoft.com/en-us/library/ms171645.aspx

This is Creating an Explorer Style Interface with the ListView and TreeView Controls Using the Designer. 这是使用设计器使用ListView和TreeView控件创建一个Explorer风格的接口。

So all is well, howerver, is you set it to the root of C to scan all the folders and files etc. I receive {"Access to the path '<path to file' is denied."} 因此,一切都很好,但是,是否将其设置为C的根目录以扫描所有文件夹和文件等。我收到{"Access to the path '<path to file' is denied."}

VS 2010 points this spot that is the issue. VS 2010指出了这个问题所在。

subSubDirs = subDir.GetDirectories();

I can put a try catch around this are, howerver, after the exception is thrown the app doesn't continue. 但是,我可以尝试解决这个问题,但是在引发异常之后,该应用程序将无法继续运行。

Is there a way I can skip directories that the app cannot access? 有没有一种方法可以跳过应用程序无法访问的目录?

You might have the try catch in the wrong place. 您可能将try catch放在错误的位置。 Based on the code in the walkthrough you could put the try catch like this: 根据演练中的代码,您可以像这样放置try catch:

Replace: 更换:

subSubDirs = subDir.GetDirectories();

with this: 有了这个:

try 
{
    subSubDirs = subDir.GetDirectories();
}
catch(UnauthorizedAccessException uae)
{
  //log that subDir.GetDirectories was not possible
}

Also, the line: 另外,该行:

if (subSubDirs.Length != 0)

should be changed to: 应该更改为:

if (subSubDirs != null && subSubDirs.Length != 0)

You get the exception because the calling account doesn't have access rights to folders like System Volume Information . 之所以会出现这种异常,是因为主叫帐户无权访问“ System Volume Information类的文件夹。 You can get around this some by using Linq and skipping folders that are marked System or Hidden . 您可以通过使用LINQ和跳过被标记的文件夹解决这个问题的一些 SystemHidden

DirectoryInfo root = new DirectoryInfo(@"C:\");

Func<FileSystemInfo, Boolean> predicate = dir =>
    (dir.Attributes & FileAttributes.System) != FileAttributes.System &&
    (dir.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden;

IEnumerable<FileSystemInfo> directories = root.GetDirectories().Where(predicate);

foreach (DirectoryInfo directory in directories) {
    try {
        Trace.WriteLine(directory.Name);
        DirectoryInfo[] subdirectories = directory.GetDirectories();
    }
    catch (System.UnauthorizedAccessException) {
        Trace.WriteLine("Insufficient access rights.");
    }
}

Trace.WriteLine("End of application.");

This is not solution for every scenario though, and will fail on some files and folders. 但是,这并不是每种情况的解决方案,并且在某些文件和文件夹上将失败。 There is no easy solution using the existing API; 使用现有的API没有简单的解决方案。 you may want to look into getting file and directory information through WMI instead. 您可能想研究通过WMI获取文件和目录信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM