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

C#でディレクトリのアクセス権を取得するコードを紹介します。

概要

ディレクトリのアクセス権を取得するには、.NET Core、.NET 5以降では FileSystemAclExtensions クラスの GetAccessControlメソッドを利用します。
.NET Frameworkアプリケーションでは、

プログラム: .NET 5 以降

Windows Formアプリケーションを作成します。

UI

下図のフォームを作成します。今回のプログラムでは button1 は利用しません。

コード

以下のコードを記述します。
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;

namespace AccessPermissionGet
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
      string folderPath = @"C:\Windows";

      //見出し
      System.Diagnostics.Debug.WriteLine("AreAccessRulesCanonical\tAreAccessRulesProtected");
      textBox1.Text += "AreAccessRulesCanonical\tAreAccessRulesProtected" + "\r\n";

      //ディレクトリのセキュリティオブジェクト取得
      DirectoryInfo di = new DirectoryInfo(folderPath);
      DirectorySecurity security = FileSystemAclExtensions.GetAccessControl(di);

      //アクセス許可の並び順、継承からの保護
      System.Diagnostics.Debug.WriteLine(security.AreAccessRulesCanonical + "\t" + security.AreAccessRulesProtected);
      textBox1.Text += security.AreAccessRulesCanonical + "\t" + security.AreAccessRulesProtected + "\r\n";

      //見出し
      string ace = "AccessControlType"
          + "\tAccountName"
          + "\tFileSystemRights"
          + "\tIsInherited"
          + "\tInheritanceFlags"
          + "\tPropagationFlags";
      System.Diagnostics.Debug.WriteLine(ace);
      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文を利用する場合
      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";
      } 
      */
    }
  }
}

解説

DirectoryInfo オブジェクトを作成し、FileSystemAclExtensionsオブジェクトのGetAccessControlメソッドを呼び出し、DirectorySecurity オブジェクトを取得します。
  DirectoryInfo di = new DirectoryInfo(folderPath);
  DirectorySecurity security = FileSystemAclExtensions.GetAccessControl(di);

ディレクトリのアクセス許可の並び順が正規順序か、継承からの保護の情報をテキストボックスに表示します。
  textBox1.Text += security.AreAccessRulesCanonical + "\t" + security.AreAccessRulesProtected + "\r\n";

DirectorySecurity オブジェクトの GetAccessRules メソッドを呼び出し、AuthorizationRuleCollection オブジェクトを取得します。
  AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));

ループ処理で、AuthorizationRuleCollection オブジェクトの要素にアクセスし、アクセス権の情報をテキストボックスに表示します。
  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";
  }

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[button2]をクリックします。ディレクトリのアクセス権の情報がテキストボックスに表示されます。

プログラム例:.NET Framework

.NET FrameworkのWindows Formアプリケーションを作成します。

UI

下図のURLを作成します。今回のプログラムでは[ファイルアクセス権取得]の[実行]ボタンは利用しません。

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AccessPermissionGetNetFramework
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void button_GetDirectoryAccessPermission_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);
      //アクセス許可の並び順、継承からの保護
      System.Diagnostics.Debug.WriteLine(security.AreAccessRulesCanonical + "\t" + security.AreAccessRulesProtected);
      textBox1.Text += security.AreAccessRulesCanonical + "\t" + security.AreAccessRulesProtected + "\r\n";

      //見出し
      string ace = "AccessControlType"
          + "\tAccountName"
          + "\tFileSystemRights"
          + "\tIsInherited"
          + "\tInheritanceFlags"
          + "\tPropagationFlags";
      System.Diagnostics.Debug.WriteLine(ace);
      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文を利用する場合
      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";
      } 
      */

    }
  }
}

解説

Directory.GetAccessControl()メソッドを呼び出し、DirectorySecurity オブジェクトを取得します。
DirectorySecurity security = Directory.GetAccessControl(folderPath);

ディレクトリのアクセス許可の並び順が正規順序か、継承からの保護の情報をテキストボックスに表示します。
textBox1.Text += security.AreAccessRulesCanonical + "\t" + security.AreAccessRulesProtected + "\r\n";

DirectorySecurity オブジェクトの GetAccessRules メソッドを呼び出し、AuthorizationRuleCollection オブジェクトを取得します。 このコレクションにディレクトリのアクセス権が記録されています。
AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));

ループ処理でAuthorizationRuleCollection オブジェクトの要素にアクセスし、アクセス権の情報をテキストボックスに出力します。
  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";
  }

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[ディレクトリアクセス権の取得]の[実行]ボタンをクリックします。ディレクトリのアクセス権がテキストボックスに表示されます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-22
改訂日: 2022-11-03
作成日: 2010-11-21
iPentec all rights reserverd.