[C#] ディレクトリのアクセス権を取得する

61 篇文章 1 订阅
45 篇文章 0 订阅

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";
  } 
}

実行結果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值