Change permissions of folders

10,509

You could try something like this:

var dirInfo = new DirectoryInfo(folder);
dirInfo.Attributes &= ~FileAttributes.ReadOnly;

This uses the bitwise logical AND operator (&=) to append to the existing Attributes property the inverse of FileAttributes.ReadOnly (because ~ is bitwise NOT).

Share:
10,509
leon22
Author by

leon22

Updated on June 04, 2022

Comments

  • leon22
    leon22 almost 2 years

    I want to change some folder permissions (set to Read-Only) to ReadWriteExecute!

    I wrote this code, but the folder permission is still Read-Only:

    private void ChangePermissions(string folder)
    {
        string userName = Environment.UserName;
    
        FileSystemAccessRule accessRule = new FileSystemAccessRule(userName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit 
                    | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
    
        DirectoryInfo directoryInfo = new DirectoryInfo(folder);
        DirectorySecurity directorySec = directoryInfo.GetAccessControl();
    
    
        directorySec.AddAccessRule(accessRule);
        directoryInfo.SetAccessControl(directorySec);
    }
    

    If I want delete this directory with Directory.Delete(folder, true) I get this error message:

    "Access to the path 'entries' is denied."

    Sure, the permissions are still Read-Only!

    What is wrong here?

  • leon22
    leon22 about 12 years
    Same error. The 'entries' path is a file in the folder, maybe I must recursively change the permissions?! (but I dont understand why the Read-Only flag is still set to root folder?)
  • Robbie
    Robbie about 12 years
    If you need to recursively change the file permissions, this SO post might help: stackoverflow.com/questions/191399/…
  • leon22
    leon22 about 12 years
    Thx. With the code from stackoverflow.com/questions/191399/… all went fine!
  • Robbie
    Robbie about 4 years
    @YoushaAleayoub permissions are handled using FileAttributes