C# - Set Directory Permissions for All Users in Windows 7

后端 未结 2 1313
感动是毒
感动是毒 2020-11-28 09:28

This should be a fairly simple problem, but for some reason I can\'t seem to get this to work. All I\'d like to do is set the permissions on a given directory to allow full

2条回答
  •  伪装坚强ぢ
    2020-11-28 10:14

    You also need to call SetAccessControl to apply the changes.

    ds = di.GetAccessControl();
    ds.AddAccessRule(fsar);
    di.SetAccessControl(ds); // nothing happens until you do this
    

    It seems that the examples on MSDN are sorely lacking in detail, as discussed here. I hacked the code from this article to get the following which behaves well:

    static bool SetAcl()
    {
        FileSystemRights Rights = (FileSystemRights)0;
        Rights = FileSystemRights.FullControl;
    
        // *** Add Access Rule to the actual directory itself
        FileSystemAccessRule AccessRule = new FileSystemAccessRule("Users", Rights,
                                    InheritanceFlags.None,
                                    PropagationFlags.NoPropagateInherit,
                                    AccessControlType.Allow);
    
        DirectoryInfo Info = new DirectoryInfo(destinationDirectory);
        DirectorySecurity Security = Info.GetAccessControl(AccessControlSections.Access);
    
        bool Result = false;
        Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);
    
        if (!Result)
            return false;
    
        // *** Always allow objects to inherit on a directory
        InheritanceFlags iFlags = InheritanceFlags.ObjectInherit;
        iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
    
        // *** Add Access rule for the inheritance
        AccessRule = new FileSystemAccessRule("Users", Rights,
                                    iFlags,
                                    PropagationFlags.InheritOnly,
                                    AccessControlType.Allow);
        Result = false;
        Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);
    
        if (!Result)
            return false;
    
        Info.SetAccessControl(Security);
    
        return true;
    }
    

提交回复
热议问题