1

我试图将目录列表添加到TreeView系统,但我遇到了似乎是用户访问问题的问题。我已经尝试了解决这个问题的各种步骤,其中没有一个能够奏效。其中包括:更改解决方案清单文件中的安全性,使用try catch跳过我无法访问的文件,并更改我的Windows用户文件夹设置以完成控制(管理员)。我在网络中寻找了类似问题的答案,大多数人都使用了try catch系统。这对我的系统不起作用,因为所有东西都冻结了,它就坐在那里。然后,程序就像在我的整个计算机上没有找到单个目录一样。我的代码包括:尝试将目录添加到TreeView时发生UnauthorizedAccessException

public Folder_Browser() 
    { 
     InitializeComponent(); 
     MapDirectory(); 
    } 

    private void MapDirectory() 
    { 
     TreeNode rootNode; 
     DirectoryInfo dirPrograms = new DirectoryInfo(@"/"); 
     DriveInfo[] loadedDrives = DriveInfo.GetDrives(); 

     foreach (DriveInfo dr in loadedDrives) 
     { 
      if (dr.DriveType != DriveType.Removable) 
      { 
       DirectoryInfo info = new DirectoryInfo(dr.Name); 

       if (info.Exists) 
       { 
        rootNode = new TreeNode(info.Name); 
        rootNode.Tag = info; 
        GetDirectories(info.GetDirectories(), rootNode); 
        treeView1.Nodes.Add(rootNode); 
       } 
      } 
     } 
    } 

    private void GetDirectories(DirectoryInfo[] subDirs, TreeNode nodeToAddTo) 
    { 
     TreeNode aNode; 
     DirectoryInfo[] subSubDirs; 

     foreach (DirectoryInfo subDir in subDirs) 

     { 
      aNode = new TreeNode(subDir.Name, 0, 0); 
      aNode.Tag = subDir; 
      aNode.ImageKey = "folder"; 
      try 
      { 
       subSubDirs = subDir.GetDirectories(); 
       //ERROR HERE^^^^^^^ 
       if (subSubDirs != null && subSubDirs.Length != 0) 
       { 
        GetDirectories(subSubDirs, aNode); 
       } 
        nodeToAddTo.Nodes.Add(aNode); 
      } 
      catch (System.UnauthorizedAccessException) 
      { 

      } 

     } 
    } 

每次我试图实现别人的解决这种问题,我只是没有得到任何形式的目录列表中走出来。该程序占用了太多的资源,忽略了它无法触及的文件夹。有没有简单的我忽略了?或者这种方法是不可能的?任何帮助表示赞赏,干杯。

回答

0

如果任何人有这样的问题,我设法找到解决方案,解决我的问题。需要添加一个额外的功能,控制程序如何与元素(目录)进行交互。该程序使用相同的源代码跳过解决方案无法访问的目录(尝试捕获),但使用System.Security.AccessControl允许它继续并找到可以访问的目录。功能如下:

using System.Security.AccessControl;

public static void SetAccessRule(string directory) 
    { 
     System.Security.AccessControl.DirectorySecurity Security = System.IO.Directory.GetAccessControl(directory); 
     FileSystemAccessRule accountAllow = new FileSystemAccessRule(Environment.UserDomainName + "\\" + Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow); 
     Security.AddAccessRule(accountAllow); 
    } 

这个解决方案的更多信息,以及我是如何走过来的,可以在这里找到:

http://social.msdn.microsoft.com/Forums/vstudio/en-US/206cfa9d-3e5b-43be-840f-49a221e10749/c-unauthorizedaccessexception-when-trying-to-programmically-copying-folder

相关问题