Compartilhar via


Code Snippet: Setting NTFS permissions

My previous post shows how to use Windows32.Security to read and set permissions to the registry. Doing the same for a NTFS is even simpler:

public bool TestNTFSPermissions(string path, string userName)

{

      SecurityDescriptor secDesc = SecurityDescriptor.GetFileSecurity(path, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION);

      Dacl dacl = secDesc.Dacl;

      return TestAcl(dacl, userName);

}

public void SetNTFSPermissions(string path, string userName)

{

      SecurityDescriptor secDesc = SecurityDescriptor.GetFileSecurity(path, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION);

      Dacl dacl = secDesc.Dacl;

      Sid sidUser = new Sid (userName);

      // allow: folder, subfolder and files

      dacl.AddAce (new AceAccessAllowed (sidUser, AccessType.GENERIC_ALL, AceFlags.OBJECT_INHERIT_ACE | AceFlags.CONTAINER_INHERIT_ACE));

      secDesc.SetDacl(dacl);

      secDesc.SetFileSecurity(path, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION);

}

There is one caviat - I couldn't find a way to automagically apply a setting to a folder and recursively to all the subfolders & files. The following snippet takes care of that:

public void SetRecursiveNTFSPermissions(string path, string userName)

{

      SetNTFSPermissions(path,userName);

      foreach(string file in Directory.GetFiles(path))

            SetNTFSPermissions(file,userName);

      foreach(string dir in Directory.GetDirectories(path))

            SetRecursiveNTFSPermissions(dir,userName);

}

Comments