C # Set file permissions,

Source: Internet
Author: User

C # Set file permissions,

During development, we often use IO operations, such as creating and deleting files. There are also many such requirements in the project. We often encode these operations, but set the file permissions. Such operations may be performed manually, this section describes how to dynamically set permissions for files using code.

In DOtNet, The FileSystemAccessRule class is used for File Permission operations.

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

  public FileSystemAccessRule(            IdentityReference identity,            FileSystemRights fileSystemRights,            AccessControlType type )            : this(                identity,                AccessMaskFromRights( fileSystemRights, type ),                false,                InheritanceFlags.None,                PropagationFlags.None,                type )        {        }        public FileSystemAccessRule(            String identity,            FileSystemRights fileSystemRights,            AccessControlType type )            : this(                new NTAccount(identity),                AccessMaskFromRights( fileSystemRights, type ),                false,                InheritanceFlags.None,                PropagationFlags.None,                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( base.AccessMask ); }        }         internal static int AccessMaskFromRights( FileSystemRights fileSystemRights, AccessControlType controlType )        {            if (fileSystemRights < (FileSystemRights) 0 || fileSystemRights > FileSystemRights.FullControl)                throw new ArgumentOutOfRangeException("fileSystemRights", Environment.GetResourceString("Argument_InvalidEnumValue", fileSystemRights, "FileSystemRights"));            Contract.EndContractBlock();            if (controlType == AccessControlType.Allow) {                fileSystemRights |= FileSystemRights.Synchronize;            }            else if (controlType == AccessControlType.Deny) {                if (fileSystemRights != FileSystemRights.FullControl &&                    fileSystemRights != (FileSystemRights.FullControl & ~FileSystemRights.DeleteSubdirectoriesAndFiles))                    fileSystemRights &= ~FileSystemRights.Synchronize;            }            return ( int )fileSystemRights;        }        internal static FileSystemRights RightsFromAccessMask( int accessMask )        {            return ( FileSystemRights )accessMask;        }    }

2. Because FileSystemAccessRule inherits from AccessRule, let's take a look at the source code of AccessRule:

/// <Summary> /// a combination of the user ID, access mask, and access control type (allowed or denied. <See cref = "T: System. Security. AccessControl. AccessRule"/> the object also contains information about how sub-objects inherit rules and how inheritance is propagated. /// </Summary> public abstract class AccessRule: AuthorizationRule {// <summary> /// use the specified value to initialize <see cref = "T: System. security. accessControl. A new instance of the AccessRule class. /// </Summary> /// <param name = "identity"> ID of the application access rule. This parameter must be an object that can be forcibly converted to <see cref = "T: System. Security. Principal. SecurityIdentifier"/>. </Param> <param name = "accessMask"> access mask of the rule. The access mask is a 32-bit set of anonymous bits. Its meaning is defined by each integrator. </Param> <param name = "isInherited"> true if the rule inherits from the parent container. </Param> <param name = "inheritanceFlags"> inherits the attributes of an access rule. </Param> <param name = "propagationFlags"> whether the inherited access rules are automatically propagated. If <paramref name = "inheritanceFlags"/> is set to <see cref = "F: System. Security. AccessControl. InheritanceFlags. None"/>, the propagation flag is ignored. </Param> <param name = "type"> a valid access control type. </Param> <exception cref = "T: System. the value of the ArgumentException "> <paramref name =" identity "/> parameter cannot be forcibly converted to <see cref =" T: System. security. principal. securityIdentifier "/>, or the <paramref name =" type "/> parameter contains invalid values. </Exception> <exception cref = "T: System. argumentOutOfRangeException "> <paramref name =" accessMask "/> the parameter value is zero, or the <paramref name = "inheritanceFlags"/> or <paramref name = "propagationFlags"/> parameter contains unrecognized flag values. </Exception> protected AccessRule (IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags, AccessControlType type ); /// <summary> /// obtain the <see cref = "T: System. security. accessControl. <see cref = "T: System. security. accessControl. accessControlType "/> object. /// </Summary> ///// <returns> /// <see cref = "T: System. security. accessControl. <see cref = "T: System. security. accessControl. accessControlType "/> object. /// </Returns> public AccessControlType {get ;}}

It seems that the class for setting file permissions in DotNet provides several specific file setting operation codes:

3. Get the directory permission list:

/// <Summary> /// obtain the directory permission list /// </summary> /// <param name = "path"> directory path. </Param> // <returns> indicates the permission list of the Directory </returns> public IList <FileSystemRights> GetDirectoryPermission (string path) {try {if (! DirectoryExists (path) return null; IList <FileSystemRights> result = new List <FileSystemRights> (); var dSecurity = Directory. getAccessControl (new DirectoryInfo (path ). fullName); foreach (FileSystemAccessRule rule in dSecurity. getAccessRules (true, true, typeof (NTAccount) result. add (rule. fileSystemRights); return result;} catch (Exception e) {throw new Exception (e. message, e );}}

4. Set Directory Permissions

/// <Summary> /// set the directory permission /// </summary> /// <param name = "path"> directory path. </Param> /// <param name = "permission"> permission set on the directory. </Param> /// <returns> indicates whether the permission value is applied to the directory. </Returns> public bool SetDirectoryPermission (string path, FileSystemRights permission) {try {if (! DirectoryExists (path) return false; var accessRule = new FileSystemAccessRule ("Users", permission, 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) return false; const InheritanceFlags iFlags = InheritanceFlags. containerInherit | InheritanceFlags. objectInherit; accessRule = new FileSystemAccessRule ("Users", permission, iFlags, PropagationFlags. inheritOnly, AccessControlType. allow); security. modifyAccessRule (AccessControlModification. add, accessRule, out result); if (! Result) return false; info. SetAccessControl (security); return true;} catch (Exception e) {throw new Exception (e. Message, e );}}

5. Set the directory permission list

/// <Summary> /// set the directory permission list /// </summary> /// <param name = "path"> directory path. </Param> /// <param name = "permissions"> permission set on the directory. </Param> /// <returns> indicates whether the permission value is applied to the directory. </Returns> public bool SetDirectoryPermissions (string path, FileSystemRights [] permissions) {try {if (! DirectoryExists (path) | permissions = null |! Permissions. Any () return false; foreach (var permission in permissions) if (! SetDirectoryPermission (path, permission) return false; return true;} catch (Exception e) {throw new Exception (e. Message, e );}}

The above is a brief introduction to file permission settings.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.