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

C#でディレクトリのアクセス権を削除する方法を紹介します。

概要

C#のプログラムでディレクトリに追加したアクセス権を削除します。
補足
対象となるディレクトリのみにアクセス権を追加した場合はこの記事で紹介する方法でアクセス権を削除できますが、 アクセス権が親フォルダから継承されている場合はこの方法では削除できません。
継承されているディレクトリのアクセス権を削除する方法はこちらの記事を参照して下さい。

コード例: .NET 5 以降

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

解説

以下のコードで指定したディレクトリのセキュリティ情報(ファイルセキュリティオブジェクト)を取得します。
ディレクトリのパスから、DirectoryInfo オブジェクトを作成し、FileSystemAclExtensions.GetAccessControl()の第一引数に 取得したいディレクトリの DirectoryInfo オブジェクトを与えて呼び出して呼び出します。
GetAccessControl メソッドにより FileSecurity オブジェクトが取得できます。
  DirectoryInfo di = new DirectoryInfo(filePath);
  FileSecurity security = FileSystemAclExtensions.GetAccessControl(di);

セキュリティ情報から"everyone"のアクセス権を削除します。
  security.PurgeAccessRules(new NTAccount("everyone"));

指定したディレクトリに"everyone"のアクセス権を削除したセキュリティ情報(FileSecurity オブジェクト)を適用します。
  FileSystemAclExtensions.SetAccessControl(di, security);

コード例: .NET Framework

private void button_Remove_AccessRights(object sender, EventArgs e)
{
  string filePath = @"c:\\develop\dev";
  FileSecurity security = File.GetAccessControl(filePath);
  security.PurgeAccessRules(new NTAccount("everyone"));
  File.SetAccessControl(filePath, security);
}

解説

以下のコードで指定したディレクトリのセキュリティ情報(ファイルセキュリティオブジェクト)を取得します。
FileSecurity security = File.GetAccessControl(filePath);

セキュリティ情報から"everyone"のアクセス権を削除します。
security.PurgeAccessRules(new NTAccount("everyone"));

指定したディレクトリに"everyone"のアクセス権を削除したセキュリティ情報(ファイルセキュリティオブジェクト)を適用します。
File.SetAccessControl(filePath, security);

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