Changing permissions on child folders in C #

I am writing a DLL to change the permissions of a folder and everything below the folder. Below is the code that I have right now.

The problem occurs when I call addPermissions (). It correctly sets permissions for the dirName folder and any folder that I later create under the name dirName, but any folder that exists when adding permissions does not receive additional permissions.

Do I need to recursively set permissions for all child folders? Or is there a way to do this with a line or two code?

public class Permissions
{
    public void addPermissions(string dirName, string username)
    {
        changePermissions(dirName, username, AccessControlType.Allow);
    }

    public void revokePermissions(string dirName, string username)
    {
        changePermissions(dirName, username, AccessControlType.Deny);
    }

    private void changePermissions(string dirName, string username, AccessControlType newPermission)
    {
        DirectoryInfo myDirectoryInfo = new DirectoryInfo(dirName);

        DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();

        string user = System.Environment.UserDomainName + "\\" + username;

        myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(
            user, 
            FileSystemRights.Read | FileSystemRights.Write | FileSystemRights.ExecuteFile | FileSystemRights.Delete, 
            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 
            PropagationFlags.InheritOnly, 
            newPermission
        ));

        myDirectoryInfo.SetAccessControl(myDirectorySecurity);
    }
}
+3
source share
2 answers

. /, .

+1

, :

var dirInfo = new DirectoryInfo(dirName);
var dirSecurity = dirInfo.GetAccessControl();

// Add the DirectorySystemAccessRule to the security settings. 
dirSecurity.AddAccessRule(new FileSystemAccessRule(
    account, 
    rights, 
    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 
    PropagationFlags.None, 
    AccessControlType.Allow));

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

+5

Source: https://habr.com/ru/post/1738383/


All Articles