Tuesday, 17 March 2015

C# - Set Full Control Permission to a Directory

In C#, we can easily add full access control permission on a file or folder for an user account or everyone (Everybody) account using .NET classes Directory and DirectorySecurity.

The below C# code set the full control permission on the given directory for the given user account. It also applies the full control permissions to folder, subfolders and files.
public static void SetFullAccessPermission(string directoryPath,string username)
{
    DirectorySecurity dir_security = Directory.GetAccessControl(directoryPath);
            
    FileSystemAccessRule full_access_rule = new FileSystemAccessRule(username,
                     FileSystemRights.FullControl, InheritanceFlags.ContainerInherit |   
                     InheritanceFlags.ObjectInherit,PropagationFlags.None,
                     AccessControlType.Allow);

    dir_security.AddAccessRule(full_access_rule);

    Directory.SetAccessControl(directoryPath, dir_security);
}
In some cases, situation may require us to configure full control permission to every users (Everyone/Everybody account). In that case, get the everyone identity from the enum WellKnownSidType.WorldSid instead of giving the string "Everyone" because the string value "Everyone" differs other languages. The below C# code set full access control permission on the given directory for everyone account.
public static void SetFullAccessPermissionsForEveryone(string directoryPath)
{
    //Everyone Identity
    IdentityReference everyoneIdentity = new SecurityIdentifier(WellKnownSidType.WorldSid,
                                               null);

    DirectorySecurity dir_security = Directory.GetAccessControl(directoryPath);

    FileSystemAccessRule full_access_rule = new FileSystemAccessRule(everyoneIdentity,
                    FileSystemRights.FullControl, InheritanceFlags.ContainerInherit |   
                     InheritanceFlags.ObjectInherit,PropagationFlags.None,
                     AccessControlType.Allow);
    dir_security.AddAccessRule(full_access_rule);

    Directory.SetAccessControl(directoryPath, dir_security);
}

Advertisements
Advertisements

No comments:

Post a Comment