Search code examples
c#file-permissions.net-core

How to modify file access control in .NET Core


I'm trying to change the permissions of a file in .NET Core. However, it seems that FileInfo doesn't have any SetAccessControl anymore.

// Create a new FileInfo object.
FileInfo fInfo = new FileInfo(FileName);

// Get a FileSecurity object that represents the 
// current security settings.
FileSecurity fSecurity = fInfo.GetAccessControl();

// Add the FileSystemAccessRule to the security settings. 
fSecurity.AddAccessRule(new FileSystemAccessRule(Account,
                                                Rights,
                                                ControlType));

// Set the new access settings.
fInfo.SetAccessControl(fSecurity);

The goal is just to add execution right to the current owner of a file (which is not Windows or Unix specific feature).

Any clues on how to do that on .NET Core ?


Solution

  • How to Get and modify User Group Other Rights on Windows

    I finally implement the Windows file permission access:

    1. Get the file security:

          var security = new FileSecurity(fileSystemInfoFullName, 
                    AccessControlSections.Owner | 
                    AccessControlSections.Group |
                    AccessControlSections.Access);
    

    2. Get the authorization rules:

    var authorizationRules = security.GetAccessRules(true, true, typeof(NTAccount));
    

    3. Get the authorization rules for the owner:

    var owner = security.GetOwner(typeof(NTAccount));
    foreach (AuthorizationRule rule in authorizationRules)
    {
        FileSystemAccessRule fileRule = rule as FileSystemAccessRule;
        if (fileRule != null)
        {
            if (owner != null && fileRule.IdentityReference == owner)
            {
                 if (fileRule.FileSystemRights.HasFlag(FileSystemRights.ExecuteFile) ||
                    fileRule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||
                    fileRule.FileSystemRights.HasFlag(FileSystemRights.FullControl))
                {
                    ownerRights.IsExecutable = true;
                }
            }
            else if (group != null && fileRule.IdentityReference == group)
            {
                // TO BE CONTINUED...
            }
        }
    }
    

    4. Add a rule for owner:

    security.ModifyAccessRule(AccessControlModification.Add,
        new FileSystemAccessRule(owner, FileSystemRights.Modify, AccessControlType.Allow),
        out bool modified);
    

    5. Bonus

    How to get the group and others, or ... my definition of something equivalent ?

    var group = security.GetGroup(typeof(NTAccount));
    
    var others = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null)
                     .Translate(typeof(NTAccount));
    

    Note: This code comes from my open source project Lx.Shell