在C#.NET中设置NTFS权限

Nil*_*l B 5 .net c# permissions ntfs

如何在C#.NET中设置NTFS权限?我试图在.NET中更改读/写权限.我是新手,请帮忙!

Apo*_*ARE 8

您应该能够使用System.Security.AccessControl名称空间来完成它.

System.Security.AccessControl;


public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
  {
     // Create a new DirectoryInfo object.
     DirectoryInfo dInfo = new DirectoryInfo(FileName);


     // Get a DirectorySecurity object that represents the 
     // current security settings.
    DirectorySecurity dSecurity = dInfo.GetAccessControl();


    // Add the FileSystemAccessRule to the security settings. 
    dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
    Rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None,
    ControlType));


    // Set the new access settings.
    dInfo.SetAccessControl(dSecurity);


 }
Run Code Online (Sandbox Code Playgroud)

示例呼叫:

//Get current user
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
//Deny writing to the file
AddDirectorySecurity(@"C:\Users\Phil\Desktop\hello.ini",user, FileSystemRights.Write, AccessControlType.Deny);
Run Code Online (Sandbox Code Playgroud)