SoFunction
Updated on 2025-03-07

How to set file permissions in C#

In development, we often use IO operations, such as creating, deleting files, etc. There are many such needs in projects. We will often encode these operations, but set the permissions of files. Such operations may be manually operated. Now we introduce an operation that uses code to dynamically set permissions for files.

When setting permissions to files in DOtNet, the FileSystemAccessRule class will be used to perform permission operations on files.

1. Now take a look at the implementation code of FileSystemAccessRule:

 public FileSystemAccessRule(
      IdentityReference identity,
      FileSystemRights fileSystemRights,
      AccessControlType type )
      : this(
        identity,
        AccessMaskFromRights( fileSystemRights, type ),
        false,
        ,
        ,
        type )
    {
    }

    public FileSystemAccessRule(
      String identity,
      FileSystemRights fileSystemRights,
      AccessControlType type )
      : this(
        new NTAccount(identity),
        AccessMaskFromRights( fileSystemRights, type ),
        false,
        ,
        ,
        type )
    {
    }

    //
    // Constructor for creating access rules for folder objects
    //

    public FileSystemAccessRule(
      IdentityReference identity,
      FileSystemRights fileSystemRights,
      InheritanceFlags inheritanceFlags,
      PropagationFlags propagationFlags,
      AccessControlType type )
      : this(
        identity,
        AccessMaskFromRights( fileSystemRights, type ),
        false,
        inheritanceFlags,
        propagationFlags,
        type )
    {
    }

    public FileSystemAccessRule(
      String identity,
      FileSystemRights fileSystemRights,
      InheritanceFlags inheritanceFlags,
      PropagationFlags propagationFlags,
      AccessControlType type )
      : this(
        new NTAccount(identity),
        AccessMaskFromRights( fileSystemRights, type ),
        false,
        inheritanceFlags,
        propagationFlags,
        type )
    {
    }
    internal FileSystemAccessRule(
      IdentityReference identity,
      int accessMask,
      bool isInherited,
      InheritanceFlags inheritanceFlags,
      PropagationFlags propagationFlags,
      AccessControlType type )
      : base(
        identity,
        accessMask,
        isInherited,
        inheritanceFlags,
        propagationFlags,
        type )
    {
    }

    #endregion

    #region Public properties

    public FileSystemRights FileSystemRights
    {
      get { return RightsFromAccessMask(  ); }
    }

 
    internal static int AccessMaskFromRights( FileSystemRights fileSystemRights, AccessControlType controlType )
    {
      if (fileSystemRights < (FileSystemRights) 0 || fileSystemRights > )
        throw new ArgumentOutOfRangeException("fileSystemRights", ("Argument_InvalidEnumValue", fileSystemRights, "FileSystemRights"));
      ();

      if (controlType == ) {
        fileSystemRights |= ;
      }
      else if (controlType == ) {
        if (fileSystemRights !=  &&
          fileSystemRights != ( & ~))
          fileSystemRights &= ~;
      }

      return ( int )fileSystemRights;
    }

    internal static FileSystemRights RightsFromAccessMask( int accessMask )
    {
      return ( FileSystemRights )accessMask;
    }

  }

2. Since FileSystemAccessRule inherits from AccessRule, now take a look at the source code of AccessRule:

/// &lt;summary&gt;
 /// Indicates a combination of the user's identity, access mask, and access control type (allow or deny).  <see cref="T:"/> Objects also contain information about how child objects inherit rules and how inheritance is propagated. /// &lt;/summary&gt;
 public abstract class AccessRule : AuthorizationRule
 {
  /// &lt;summary&gt;
  /// Initialize a new instance of the <see cref="T:"/> class with the specified value.  /// &lt;/summary&gt;
  /// <param name="identity">Application access rule identification.  This parameter must be an object that can be cast to <see cref="T:"/>.  </param><param name="accessMask">AccessMask for this rule.  The access mask is a 32-bit anonymous bit set whose meaning is defined by each integrator.  </param><param name="isInherited"> true if this rule inherits from the parent container.  </param><param name="inheritanceFlags">Inheritance properties of access rules.  </param><param name="propagationFlags">Whether the inherited access rules are propagated automatically.  If <paramref name="inheritanceFlags"/> is set to <see cref="F:"/>, the propagation flag is ignored.  </param><param name="type">Factory access control type.  </param><exception cref="T:"><paramref name="identity"/> The value of the parameter cannot be cast to <see cref="T:"/>, or the <paramref name="type"/> parameter contains invalid values.  </exception><exception cref="T:"><paramref name="accessMask"/> The value of the parameter is zero, or the <paramref name="inheritanceFlags"/> or the <paramref name="propagationFlags"/> The parameter contains unrecognized flag values.  </exception>  protected AccessRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type);
  /// &lt;summary&gt;
  /// Get the <see cref="T:"/> object associated with this <see cref="T:"/> object.  /// &lt;/summary&gt;
  /// 
  /// &lt;returns&gt;
  /// The <see cref="T:"/> object associated with this <see cref="T:"/> object.  /// &lt;/returns&gt;
  public AccessControlType AccessControlType { get; }
 }

It seems that the class in DotNet that implements file permission setting operations now provides several specific file setting operation codes:

3. Get the directory permission list:

    /// &lt;summary&gt;
    /// Get the directory permission list    /// &lt;/summary&gt;
    /// The path to the <param name="path"> directory.  </param>    /// <returns>Indicates the permission list for the directory</returns>    public IList&lt;FileSystemRights&gt; GetDirectoryPermission(string path)
    {
      try
      {
        if (!DirectoryExists(path))
          return null;

        IList&lt;FileSystemRights&gt; result = new List&lt;FileSystemRights&gt;();
        var dSecurity = (new DirectoryInfo(path).FullName);
        foreach (FileSystemAccessRule rule in (true, true, typeof(NTAccount)))
          ();

        return result;
      }
      catch (Exception e)
      {
        throw new Exception(, e);
      }
    }

4. Set directory permissions

    /// &lt;summary&gt;
    ///Set directory permissions    /// &lt;/summary&gt;
    /// The path to the <param name="path"> directory.  </param>    /// <param name="permission">Permission set on the directory.  </param>    /// <returns> indicates whether the value of permissions is applied on the directory.  </returns>    public bool SetDirectoryPermission(string path, FileSystemRights permission)
    {
      try
      {
        if (!DirectoryExists(path))
          return false;

        var accessRule = new FileSystemAccessRule("Users", permission,
                      ,
                      ,
                      );

        var info = new DirectoryInfo(path);
        var security = ();

        bool result;
        (, accessRule, out result);

        if (!result)
          return false;

        const InheritanceFlags iFlags =  | ;

        accessRule = new FileSystemAccessRule("Users", permission,
                      iFlags,
                      ,
                      );

        (, accessRule, out result);

        if (!result)
          return false;

        (security);

        return true;
      }
      catch (Exception e)
      {
        throw new Exception(, e);
      }
    }

5. Set the directory permission list

  /// &lt;summary&gt;
  /// Set directory permission list  /// &lt;/summary&gt;
  /// The path to the <param name="path"> directory.  </param>  /// <param name="permissions">Permissions set on the directory.  </param>  /// <returns> indicates whether the value of permissions is applied on the directory.  </returns>  public bool SetDirectoryPermissions(string path, FileSystemRights[] permissions)
  {
   try
   {
    if (!DirectoryExists(path) || permissions == null || !())
     return false;

    foreach (var permission in permissions)
     if (!SetDirectoryPermission(path, permission))
      return false;

    return true;
   }
   catch (Exception e)
   {
    throw new Exception(, e);
   }
  }

The above is the detailed content of the method of setting file permissions in C#. For more information about setting file permissions in C#, please pay attention to my other related articles!