Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting NTFS permissions in C#.NET

How do I set NTFS permissions in C#.NET? I am trying to change permissions for read/write in .NET. I'm a newbie, please assist!

like image 614
Nil B Avatar asked Sep 17 '11 01:09

Nil B


People also ask

How do I fix NTFS permissions?

Reset NTFS security permissions You can use the command: takeown /R /F * before launching the ICACLS. But run the command with caution because it may cause system broken. ICACLS command will reset the permissions of all the folders, files and subfolders.

What are the permissions for NTFS?

There are three types of share permissions: Full Control, Change, and Read. Full Control: Enables users to “read,” “change,” as well as edit permissions and take ownership of files. Change: Change means that user can read/execute/write/delete folders/files within share.


1 Answers

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);
like image 88
apollosoftware.org Avatar answered Oct 13 '22 10:10

apollosoftware.org