I have an EventHandler that checks permission level.
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() returns only "Allow" or "Deny" but I need to get something this:
View: True
Add: True
Modify: False
Delete: False
How can i achieve this ?
You have to change AccessRule in your foreach to FileSystemAccessRule. Then you have access to the property FileSystemRights. This answer explains how to get the rights.
Short version, on how to check if User or Group has Permission:
//Example: Change
bool hasChangePermission = rule.FileSystemRights.HasFlag(FileSystemRights.ChangePermissions);
//Example: Write
bool hasWritePermission = rule.FileSystemRights.HasFlag(FileSystemRights.Write);
Here's a small example method:
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);
}