継承されているディレクトリのアクセス権を変更、削除する - C#

継承されているディレクトリのアクセス権を変更、削除するコードを紹介します。

概要

ファイルやフォルダに追加されたアクセス権を削除する場合はこちらこちらの方法でアクセス権を削除できますが、ファイルやフォルダのアクセス権が親フォルダのアクセス権を継承している場合は前述の方法では削除できません。アクセス権が継承されている場合は、まず、アクセス権の継承を保護した後にディレクトリのアクセス権を変更する必要があります。

コード: .NET 5以降

private void button6_Click(object sender, EventArgs e)
{
  string filePath = @"c:\\develop\dev";
  DirectoryInfo di = new DirectoryInfo(filePath);
  DirectorySecurity security = FileSystemAclExtensions.GetAccessControl(di);
  security.SetAccessRuleProtection(true, true);
  security.PurgeAccessRules(new NTAccount("Users"));
  FileSystemAclExtensions.SetAccessControl(di, security);
}

解説

.NET 5以降の場合は、DirectoryInfo オブジェクトを作成し、FileSystemAclExtensions.GetAccessControl() メソッドで、 DirectorySecurity オブジェクトを作成します。
  DirectoryInfo di = new DirectoryInfo(filePath);
  DirectorySecurity security = FileSystemAclExtensions.GetAccessControl(di);

以下のコードにより、継承されているディレクトリのアクセス権を変更できるようにします。 一番目の引数で継承をするかしないかを設定します。上記の例ではtrueですので、継承を保護する設定になり、アクセス権の変更ができます。 2番目の引数は継承されたアクセス権を保存するかの設定です。上記の例ではtrueに設定されていますので、継承されたアクセス権はそのままディレクトリに残った状態になります。 (1番目の引数をTrueにしてアクセス権を継承させた場合は、アクセス権が継承されるためディレクトリには継承されたアクセス権が付与されるため、2番目の引数は無視されます。)
  security.SetAccessRuleProtection(true, true);

アクセス権を削除します。今回の例ではUsersのアクセス権を削除しています。
  security.PurgeAccessRules(new NTAccount("Users"));

セキュリティオブジェクトをc:\develop\dev フォルダに適応します。
  FileSystemAclExtensions.SetAccessControl(di, security);

コード: .NET Framework

private void button_RemoveInheritanceDir_Click(object sender, EventArgs e)
{
  string filePath = @"c:\\develop\dev";
  DirectorySecurity security = Directory.GetAccessControl(filePath);
  security.SetAccessRuleProtection(true, true);
  security.PurgeAccessRules(new NTAccount("Users"));
  Directory.SetAccessControl(filePath, security);
}

解説

下記のコードで指定したディレクトリのセキュリティ情報(ファイルセキュリティオブジェクト)を取得します。

.NET Framework アプリケーションの場合は、ディレクトリのパスを与えて、 Directory.GetAccessControl()メソッドを呼び出すことで、DirectorySecurity オブジェクトを作成します。
  DirectorySecurity security = Directory.GetAccessControl(filePath);

SetAccessRuleProtectionの呼び出しは.NET の場合と同様です。
security.SetAccessRuleProtection(true, true);

アクセス権を削除します。今回の例ではUsersのアクセス権を削除しています。
security.PurgeAccessRules(new NTAccount("Users"));

セキュリティオブジェクトをc:\develop\dev フォルダに適応します。.NET Frameworkの場合は、SetAccessControlメソッドの第一に引数に、 ディレクトリのパスを与えます。
Directory.SetAccessControl(filePath, security);

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2010-11-30
iPentec all rights reserverd.