August 28, 2012

Modifying Directory Access Rules

Here is the routine to do the work:
 
// Adds an ACL entry on the specified directory for the specified account.
public static void AddDirectorySecurity(
    string folderName, 
 string account, 
 FileSystemRights rights, 
 AccessControlType controlType)
{
    // Create a new DirectoryInfo object.
    DirectoryInfo dirInfo = new DirectoryInfo(folderName);

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

    // Add the FileSystemAccessRule to the security settings. 
    dSecurity.AddAccessRule(new FileSystemAccessRule(account,
                                                    rights,
                                                    controlType));

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

Sample usage of the routine:
DirectoryInfo targetDir = GetDirectoryInfo();    
// eg Deny the current user write permission on a given directory       
AddDirectorySecurity(targetDir.FullName, Environment.UserName, 
    FileSystemRights.Write, AccessControlType.Deny);

There is a remove as well:
// Removes an ACL entry on the specified directory for the specified account.
public static void RemoveDirectorySecurity(string folderName, string account, FileSystemRights rights, AccessControlType controlType)
{
    // Create a new DirectoryInfo object.
    DirectoryInfo dInfo = new DirectoryInfo(folderName);

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

    // Add the FileSystemAccessRule to the security settings. 
    dSecurity.RemoveAccessRule(new FileSystemAccessRule(account,
                                                    rights,
                                                    controlType));

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

}
These methods are useful when unit testing writing to a directory without the appropriate permission.

No comments: