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

后端 未结 2 1312
感动是毒
感动是毒 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:15

    David Heffernan answer does not work on a non-English machine, where trying to set the permissions on "Users" fails with an IdentityNotMapped exception. The following code will work everywhere, by using WellKnownSidType.BuiltinUsersSid instead:

    static void SetFullControlPermissionsToEveryone(string path)
    {
        const FileSystemRights rights = FileSystemRights.FullControl;
    
        var allUsers = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
    
        // Add Access Rule to the actual directory itself
        var accessRule = new FileSystemAccessRule(
            allUsers,
            rights,
            InheritanceFlags.None,
            PropagationFlags.NoPropagateInherit,
            AccessControlType.Allow);
    
        var info = new DirectoryInfo(path);
        var security = info.GetAccessControl(AccessControlSections.Access);
    
        bool result;
        security.ModifyAccessRule(AccessControlModification.Set, accessRule, out result);
    
        if (!result)
        {
            throw new InvalidOperationException("Failed to give full-control permission to all users for path " + path);
        }
    
        // add inheritance
        var inheritedAccessRule = new FileSystemAccessRule(
            allUsers,
            rights,
            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
            PropagationFlags.InheritOnly,
            AccessControlType.Allow);
    
        bool inheritedResult;
        security.ModifyAccessRule(AccessControlModification.Add, inheritedAccessRule, out inheritedResult);
    
        if (!inheritedResult)
        {
            throw new InvalidOperationException("Failed to give full-control permission inheritance to all users for " + path);
        }
    
        info.SetAccessControl(security);
    }
    

提交回复
热议问题