在开发中,我们经常会使用IO操作,例如创建,删除文件等操作。在项目中这样的需求也较多,我们也会经常对这些操作进行编码,但是对文件的权限进行设置,这样的操作可能会手动操作,现在介绍一种采用代码动态对文件设置权限的操作。

在对文件进行权限设置在DOtNet中,会采用FileSystemAcce***ule类进行文件的权限操作。

1.现在看一下FileSystemAcce***ule的实现代码:

publicFileSystemAcce***ule(IdentityReferenceidentity,FileSystemRightsfileSystemRights,AccessControlTypetype):this(identity,AccessMaskFromRights(fileSystemRights,type),false,InheritanceFlags.None,PropagationFlags.None,type){}publicFileSystemAcce***ule(Stringidentity,FileSystemRightsfileSystemRights,AccessControlTypetype):this(newNTAccount(identity),AccessMaskFromRights(fileSystemRights,type),false,InheritanceFlags.None,PropagationFlags.None,type){}////Constructorforcreatingaccessrulesforfolderobjects//publicFileSystemAcce***ule(IdentityReferenceidentity,FileSystemRightsfileSystemRights,InheritanceFlagsinheritanceFlags,PropagationFlagspropagationFlags,AccessControlTypetype):this(identity,AccessMaskFromRights(fileSystemRights,type),false,inheritanceFlags,propagationFlags,type){}publicFileSystemAcce***ule(Stringidentity,FileSystemRightsfileSystemRights,InheritanceFlagsinheritanceFlags,PropagationFlagspropagationFlags,AccessControlTypetype):this(newNTAccount(identity),AccessMaskFromRights(fileSystemRights,type),false,inheritanceFlags,propagationFlags,type){}internalFileSystemAcce***ule(IdentityReferenceidentity,intaccessMask,boolisInherited,InheritanceFlagsinheritanceFlags,PropagationFlagspropagationFlags,AccessControlTypetype):base(identity,accessMask,isInherited,inheritanceFlags,propagationFlags,type){}#endregion#regionPublicpropertiespublicFileSystemRightsFileSystemRights{get{returnRightsFromAccessMask(base.AccessMask);}}internalstaticintAccessMaskFromRights(FileSystemRightsfileSystemRights,AccessControlTypecontrolType){if(fileSystemRights<(FileSystemRights)0||fileSystemRights>FileSystemRights.FullControl)thrownewArgumentOutOfRangeException("fileSystemRights",Environment.GetResourceString("Argument_InvalidEnumValue",fileSystemRights,"FileSystemRights"));Contract.EndContractBlock();if(controlType==AccessControlType.Allow){fileSystemRights|=FileSystemRights.Synchronize;}elseif(controlType==AccessControlType.Deny){if(fileSystemRights!=FileSystemRights.FullControl&&fileSystemRights!=(FileSystemRights.FullControl&~FileSystemRights.DeleteSubdirectoriesAndFiles))fileSystemRights&=~FileSystemRights.Synchronize;}return(int)fileSystemRights;}internalstaticFileSystemRightsRightsFromAccessMask(intaccessMask){return(FileSystemRights)accessMask;}}

2.由于FileSystemAcce***ule继承自Acce***ule,现在看一下Acce***ule的源码:

///<summary>///表示用户的标识、访问掩码和访问控制类型(允许或拒绝)的组合。<seecref="T:System.Security.AccessControl.Acce***ule"/>对象还包含有关子对象如何继承规则以及如何传播继承的信息。///</summary>publicabstractclassAcce***ule:AuthorizationRule{///<summary>///使用指定的值初始化<seecref="T:System.Security.AccessControl.Acce***ule"/>类的一个新实例。///</summary>///<paramname="identity">应用访问规则的标识。此参数必须是可以强制转换为<seecref="T:System.Security.Principal.SecurityIdentifier"/>的对象。</param><paramname="accessMask">此规则的访问掩码。访问掩码是一个32位的匿名位集合,其含义是由每个集成器定义的。</param><paramname="isInherited">如果此规则继承自父容器,则为true。</param><paramname="inheritanceFlags">访问规则的继承属性。</param><paramname="propagationFlags">继承的访问规则是否自动传播。如果<paramrefname="inheritanceFlags"/>设置为<seecref="F:System.Security.AccessControl.InheritanceFlags.None"/>,则将忽略传播标志。</param><paramname="type">有效的访问控制类型。</param><exceptioncref="T:System.ArgumentException"><paramrefname="identity"/>参数的值不能强制转换为<seecref="T:System.Security.Principal.SecurityIdentifier"/>,或者<paramrefname="type"/>参数包含无效值。</exception><exceptioncref="T:System.ArgumentOutOfRangeException"><paramrefname="accessMask"/>参数的值为零,或者<paramrefname="inheritanceFlags"/>或<paramrefname="propagationFlags"/>参数包含无法识别的标志值。</exception>protectedAcce***ule(IdentityReferenceidentity,intaccessMask,boolisInherited,InheritanceFlagsinheritanceFlags,PropagationFlagspropagationFlags,AccessControlTypetype);///<summary>///获取与此<seecref="T:System.Security.AccessControl.Acce***ule"/>对象关联的<seecref="T:System.Security.AccessControl.AccessControlType"/>对象。///</summary>//////<returns>///与此<seecref="T:System.Security.AccessControl.Acce***ule"/>对象关联的<seecref="T:System.Security.AccessControl.AccessControlType"/>对象。///</returns>publicAccessControlTypeAccessControlType{get;}}

看了DotNet中实现文件权限设置的操作的类,现在提供几个具体的文件设置操作代码:

3.获取目录权限列表:

///<summary>///获取目录权限列表///</summary>///<paramname="path">目录的路径。</param>///<returns>指示目录的权限列表</returns>publicIList<FileSystemRights>GetDirectoryPermission(stringpath){try{if(!DirectoryExists(path))returnnull;IList<FileSystemRights>result=newList<FileSystemRights>();vardSecurity=Directory.GetAccessControl(newDirectoryInfo(path).FullName);foreach(FileSystemAcce***uleruleindSecurity.GetAcce***ules(true,true,typeof(NTAccount)))result.Add(rule.FileSystemRights);returnresult;}catch(Exceptione){thrownewException(e.Message,e);}}

4.设置目录权限

///<summary>///设置目录权限///</summary>///<paramname="path">目录的路径。</param>///<paramname="permission">在目录上设置的权限。</param>///<returns>指示是否在目录上应用权限的值。</returns>publicboolSetDirectoryPermission(stringpath,FileSystemRightspermission){try{if(!DirectoryExists(path))returnfalse;varacce***ule=newFileSystemAcce***ule("Users",permission,InheritanceFlags.None,PropagationFlags.NoPropagateInherit,AccessControlType.Allow);varinfo=newDirectoryInfo(path);varsecurity=info.GetAccessControl(AccessControlSections.Access);boolresult;security.ModifyAcce***ule(AccessControlModification.Set,acce***ule,outresult);if(!result)returnfalse;constInheritanceFlagsiFlags=InheritanceFlags.ContainerInherit|InheritanceFlags.ObjectInherit;acce***ule=newFileSystemAcce***ule("Users",permission,iFlags,PropagationFlags.InheritOnly,AccessControlType.Allow);security.ModifyAcce***ule(AccessControlModification.Add,acce***ule,outresult);if(!result)returnfalse;info.SetAccessControl(security);returntrue;}catch(Exceptione){thrownewException(e.Message,e);}}

5.设置目录权限列表

///<summary>///设置目录权限列表///</summary>///<paramname="path">目录的路径。</param>///<paramname="permissions">在目录上设置的权限。</param>///<returns>指示是否在目录上应用权限的值。</returns>publicboolSetDirectoryPermissions(stringpath,FileSystemRights[]permissions){try{if(!DirectoryExists(path)||permissions==null||!permissions.Any())returnfalse;foreach(varpermissioninpermissions)if(!SetDirectoryPermission(path,permission))returnfalse;returntrue;}catch(Exceptione){thrownewException(e.Message,e);}}

以上是对文件权限设置操作的一个简单介绍。