想用c#來設置和讀取ntfs分區上的目錄權限,找了很多資料,未果。終於發現了一段vb.net的代碼,做了修改,以C#展示給大家。
using System;
using System.Collections;
using System.IO;
using System.Security.AccessControl;
static class Tester
{
public static void Main()
{
try
{
string filename = @"f:\k"; //目標目錄
string account = @"Administrator";//用戶名
string userrights = @"RW";//權限字符串,自己定義的
AddDirectorySecurity(filename, account, userrights);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
static public void AddDirectorySecurity(string FileName, string Account, string UserRights)
{
FileSystemRights Rights = new FileSystemRights();
if (UserRights.IndexOf("R") >= 0)
{
Rights = Rights | FileSystemRights.Read;
}
if (UserRights.IndexOf("C") >= 0)
{
Rights = Rights | FileSystemRights.ChangePermissions;
}
if (UserRights.IndexOf("F") >= 0)
{
Rights = Rights | FileSystemRights.FullControl;
}
if (UserRights.IndexOf("W") >= 0)
{
Rights = Rights | FileSystemRights.Write;
}
bool ok;
DirectoryInfo dInfo = new DirectoryInfo(FileName);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
InheritanceFlags iFlags = new InheritanceFlags();
iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
FileSystemAccessRule AccessRule2 = new FileSystemAccessRule(Account, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow);
dSecurity.ModifyAccessRule(AccessControlModification.Add, AccessRule2, out ok);
dInfo.SetAccessControl(dSecurity);
//列出目標目錄所具有的權限
DirectorySecurity sec = Directory.GetAccessControl(FileName, AccessControlSections.All);
foreach (FileSystemAccessRule rule in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
Console.WriteLine("----------------------------------");
Console.WriteLine(rule.IdentityReference.Value);
if ((rule.FileSystemRights & FileSystemRights.Read) != 0)
Console.WriteLine(rule.FileSystemRights.ToString());
}
Console.Read();
}
}
對照MSDN,很容易看懂上面的代碼。 但是貌似這個程序需要以管理員身份來運行。^_^