https://www.ipentec.com/document/document.aspx?page=csharp-get-directory-access-rights
C#でディレクトリのアクセス権を取得します。
ディレクトリのアクセス権を取得する場合にはDirectoryクラスのGeetAccessControlメソッドを用います。以下はC#でディレクトリのアクセス権を取得するコードのサンプルです。
forを用いた場合
private void button2_Click(object sender, EventArgs e)
{
string folderPath = @"C:\Windows";
System.Diagnostics.Debug.WriteLine("AreAccessRulesCanonical\tAreAccessRulesProtected");
textBox1.Text += "AreAccessRulesCanonical\tAreAccessRulesProtected" + "\r\n";
DirectorySecurity security = Directory.GetAccessControl(folderPath);
textBox1.Text += security.AreAccessRulesCanonical +
"\t" + security.AreAccessRulesProtected + "\r\n";
string ace = "AccessControlType\tAccountName\tFileSystemRights\tIsInherited"
+"\tInheritanceFlags\tPropagationFlags";
textBox1.Text += ace + "\r\n";
AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));
for (int i = 0; i < rules.Count; i++) {
FileSystemAccessRule fsar = (FileSystemAccessRule)rules[i];
ace = fsar.AccessControlType
+ "\t" + (fsar.IdentityReference as NTAccount).Value
+ "\t" + fsar.FileSystemRights.ToString()
+ "\t" + fsar.IsInherited.ToString()
+ "\t" + fsar.InheritanceFlags.ToString()
+ "\t" + fsar.PropagationFlags.ToString();
textBox1.Text += ace + "\r\n";
}
}
foreachを用いた場合
private void button2_Click(object sender, EventArgs e)
{
string folderPath = @"C:\Windows";
System.Diagnostics.Debug.WriteLine("AreAccessRulesCanonical\tAreAccessRulesProtected");
textBox1.Text += "AreAccessRulesCanonical\tAreAccessRulesProtected" + "\r\n";
DirectorySecurity security = Directory.GetAccessControl(folderPath);
textBox1.Text += security.AreAccessRulesCanonical +
"\t" + security.AreAccessRulesProtected + "\r\n";
string ace = "AccessControlType\tAccountName\tFileSystemRights\tIsInherited"
+"\tInheritanceFlags\tPropagationFlags";
textBox1.Text += ace + "\r\n";
foreach (FileSystemAccessRule rule in security.GetAccessRules(true, true, typeof(NTAccount))) {
ace = rule.AccessControlType
+ "\t" + (rule.IdentityReference as NTAccount).Value
+ "\t" + rule.FileSystemRights.ToString()
+ "\t" + rule.IsInherited.ToString()
+ "\t" + rule.InheritanceFlags.ToString()
+ "\t" + rule.PropagationFlags.ToString();
System.Diagnostics.Debug.WriteLine(ace);
textBox1.Text += ace + "\r\n";
}
}