开发者

Setting NTFS permissions in C#.NET

开发者 https://www.devze.com 2023-04-05 17:05 出处:网络
How do I set NTFS permissions in C#.NET? I am trying to change permissions for read/write in .NET. I\'m a newbie, pl开发者_StackOverflow社区ease assist!you should be able to do it with

How do I set NTFS permissions in C#.NET? I am trying to change permissions for read/write in .NET. I'm a newbie, pl开发者_StackOverflow社区ease assist!


you should be able to do it with System.Security.AccessControl name space.

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);


 }

Example Call:

//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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号