2015-02-11 123 views
0

我有一个检查权限级别的EventHandler。获取文件夹的权限级别

private void button1_Click(object sender, EventArgs e) 
    { 
     int id = 1; 
      XMLPermSheet.CreateXML(); 
      string directory = textBox1.Text; 
      DirectoryInfo di = new DirectoryInfo(directory); 
      DirectoryInfo[] sdi = di.GetDirectories(); 
      foreach (DirectoryInfo tdi in sdi) 
      { 
       if (!tdi.ToString().EndsWith("System Volume Information") && !tdi.ToString().Contains("$RECYCLE.BIN")) 
       { 
        XMLPermSheet.AddPath(tdi.ToString(), id); 
        DirectorySecurity ds = tdi.GetAccessControl(); 

        foreach (AccessRule rule in ds.GetAccessRules(true, true, typeof(NTAccount))) 
        { 
         richTextBox1.AppendText(string.Format("{0} || Identity = {1}; Access = {2} \r\n", tdi.ToString(), 
         rule.IdentityReference.Value, rule.AccessControlType)); 
         XMLPermSheet.AddIdentity(rule.IdentityReference.Value.ToString(), rule.AccessControlType.ToString(), tdi.ToString()); 
        } 

        id += 1; 
       } 
      } 
    } 

rule.AccessControlType.ToString()返回只 “允许” 或 “拒绝”,但我需要得到的东西是:

查看:真
地址:真
修改:假
删除:假

我该如何做到这一点?

+0

你的意思是它的['Attributes'(https://开头msdn.microsoft.com/en-us/library/system.io.fileattributes%28v=vs.110%29.aspx)?.. – Sayse 2015-02-11 13:20:33

+0

可能是的,但这意味着文件,我需要获得文件夹属性。 – 2015-02-11 13:23:01

回答

2

您必须更改AccessRule在您的foreach到FileSystemAccessRule。然后你可以访问属性FileSystemRights。这answer解释如何获得权利。

短版,如何检查,如果用户或组具有权限:

//Example: Change  
bool hasChangePermission = rule.FileSystemRights.HasFlag(FileSystemRights.ChangePermissions); 

//Example: Write 
bool hasWritePermission = rule.FileSystemRights.HasFlag(FileSystemRights.Write); 

这里有一个小例子方法:

public string GetRuleAsString(FileSystemAccessRule rule) 
{ 
    string userName = rule.IdentityReference.Value; 

    //Example: Change  
    bool hasChangePermission = rule.FileSystemRights.HasFlag(FileSystemRights.ChangePermissions); 

    //Example: Write 
    bool hasWritePermission = rule.FileSystemRights.HasFlag(FileSystemRights.Write); 

    return String.Format("{0}\n Change: {1}\n Write: {2}", userName, hasChangePermission, hasWritePermission); 
} 
+0

好吧,但如何从DirectoryInfo对象获取AccessRights? – 2015-02-11 14:02:48

+0

我更新了我的答案。希望这可以帮助你 – 2015-02-11 14:16:21

+0

所以我做了你告诉我要做的事情,现在我有这个: var mask =(AccessRights)rule.AccessMask' 但是我得到的错误是:属性或索引器'系统.Security.AccessControl.AuthorizationRule.AccessMask'不能在这种情况下使用,因为get访问器无法访问 – 2015-02-11 14:41:10