人気ブログランキング | 話題のタグを見る

それは日常の記録

ボス日記

C#でファイルのアクセス権を設定する

意外と情報が少ないこのコード。一回わかれば、なーんだ、といった感じ。

string file = "D:\\Shared\\Book1.xml";
string user = Environment.UserDomainName + "\\" + Environment.UserName;
FileSystemAccessRule fsaRule = new FileSystemAccessRule(
   user, FileSystemRights.FullControl,  AccessControlType.Allow);

bool hasMyAccessRight = false;

//既存のアクセス権を調べる
FileSecurity security = File.GetAccessControl(file);
foreach (FileSystemAccessRule rule in
security.GetAccessRules(true, true, typeof(NTAccount)))
{
   if (((NTAccount)rule.IdentityReference).Value == user)
   {
       //すでにユーザーに関する権限があればループを抜ける。
       hasMyAccessRight = true;
       break;
   }
}
//アクセス権の設定
if (hasMyAccessRight)
{
   security.SetAccessRule(fsaRule);
}
else
{
   security.AddAccessRule(fsaRule);
}
//変更したアクセス権をファイルに設定
File.SetAccessControl(file, security);
//グループのチェックをしていないので片手落ち


---7/10
すでに設定してあるアクセス権の置き換えを行うには、まず継承の保護を解除しなければならない。(SetAccessRuleProtectionメソッドを使う。)

アクセス権は継承の仕組みがややこしいので別途ページを作った。

C#でファイルアクセス権限の付与
by hshimaji | 2010-02-23 23:30 | コンピュータ | Trackback

by hshimaji
カレンダー
S M T W T F S
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31