C#设置文件权限的方法
作者:彭泽0902 时间:2022-08-31 22:35:42
在开发中,我们经常会使用IO操作,例如创建,删除文件等操作。在项目中这样的需求也较多,我们也会经常对这些操作进行编码,但是对文件的权限进行设置,这样的操作可能会手动操作,现在介绍一种采用代码动态对文件设置权限的操作。
在对文件进行权限设置在DOtNet中,会采用FileSystemAccessRule类进行文件的权限操作。
1.现在看一下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.由于FileSystemAccessRule继承自AccessRule,现在看一下AccessRule的源码:
/// <summary>
/// 表示用户的标识、访问掩码和访问控制类型(允许或拒绝)的组合。<see cref="T:System.Security.AccessControl.AccessRule"/> 对象还包含有关子对象如何继承规则以及如何传播继承的信息。
/// </summary>
public abstract class AccessRule : AuthorizationRule
{
/// <summary>
/// 使用指定的值初始化 <see cref="T:System.Security.AccessControl.AccessRule"/> 类的一个新实例。
/// </summary>
/// <param name="identity">应用访问规则的标识。此参数必须是可以强制转换为 <see cref="T:System.Security.Principal.SecurityIdentifier"/> 的对象。</param><param name="accessMask">此规则的访问掩码。访问掩码是一个 32 位的匿名位集合,其含义是由每个集成器定义的。</param><param name="isInherited">如果此规则继承自父容器,则为 true。</param><param name="inheritanceFlags">访问规则的继承属性。</param><param name="propagationFlags">继承的访问规则是否自动传播。如果 <paramref name="inheritanceFlags"/> 设置为 <see cref="F:System.Security.AccessControl.InheritanceFlags.None"/>,则将忽略传播标志。</param><param name="type">有效的访问控制类型。</param><exception cref="T:System.ArgumentException"><paramref name="identity"/> 参数的值不能强制转换为 <see cref="T:System.Security.Principal.SecurityIdentifier"/>,或者 <paramref name="type"/> 参数包含无效值。</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="accessMask"/> 参数的值为零,或者 <paramref name="inheritanceFlags"/> 或 <paramref name="propagationFlags"/> 参数包含无法识别的标志值。</exception>
protected AccessRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type);
/// <summary>
/// 获取与此 <see cref="T:System.Security.AccessControl.AccessRule"/> 对象关联的 <see cref="T:System.Security.AccessControl.AccessControlType"/> 对象。
/// </summary>
///
/// <returns>
/// 与此 <see cref="T:System.Security.AccessControl.AccessRule"/> 对象关联的 <see cref="T:System.Security.AccessControl.AccessControlType"/> 对象。
/// </returns>
public AccessControlType AccessControlType { get; }
}
看来DotNet中实现文件权限设置的操作的类,现在提供几个具体的文件设置操作代码:
3.获取目录权限列表:
/// <summary>
/// 获取目录权限列表
/// </summary>
/// <param name="path">目录的路径。</param>
/// <returns>指示目录的权限列表</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.设置目录权限
/// <summary>
///设置目录权限
/// </summary>
/// <param name="path">目录的路径。</param>
/// <param name="permission">在目录上设置的权限。</param>
/// <returns>指示是否在目录上应用权限的值。</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.设置目录权限列表
/// <summary>
/// 设置目录权限列表
/// </summary>
/// <param name="path">目录的路径。</param>
/// <param name="permissions">在目录上设置的权限。</param>
/// <returns>指示是否在目录上应用权限的值。</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);
}
}
来源:https://cloud.tencent.com/developer/article/1013181
标签:c#,设置,文件,权限
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
My eclipse 端口占用(9360)问题解决办法
2023-05-19 02:34:32
![](https://img.aspxhome.com/file/2023/2/68542_0s.png)
Mybatis plus多租户方案的实战踩坑记录
2023-08-01 05:19:09
![](https://img.aspxhome.com/file/2023/6/57956_0s.jpg)
SpringBoot分页查询功能的实现方法
2023-07-14 02:22:21
![](https://img.aspxhome.com/file/2023/1/71651_0s.png)
springboot基于Mybatis mysql实现读写分离
2023-11-27 21:42:59
![](https://img.aspxhome.com/file/2023/5/59425_0s.png)
使用mongoTemplate实现多条件加分组查询方式
2022-05-21 01:41:51
java实现简单登录界面的实战过程
2022-02-07 20:19:51
![](https://img.aspxhome.com/file/2023/2/67152_0s.jpg)
详解Java中对象池的介绍与使用
2023-07-25 13:13:48
.net 随机生成汉字
2022-01-22 08:33:33
Spring Boot 定义系统启动任务的多种方式
2023-11-24 13:25:33
![](https://img.aspxhome.com/file/2023/7/61947_0s.png)
Java实现的微信公众号获取微信用户信息示例
2022-04-25 15:15:29
java集合与数组的相同点和不同点
2022-07-19 03:13:53
Springboot启动不检查JPA的数据源配置方式
2022-10-10 06:47:05
![](https://img.aspxhome.com/file/2023/4/68774_0s.jpg)
IntelliJ IDEA中查看当前类的所有继承关系图
2023-08-06 12:40:19
![](https://img.aspxhome.com/file/2023/6/57906_0s.png)
如何在Spring Boot应用中优雅的使用Date和LocalDateTime的教程详解
2023-03-14 04:54:11
Java使用Tess4J实现图像识别方式
2022-10-07 19:24:11
![](https://img.aspxhome.com/file/2023/9/60659_0s.png)
Android 清除SharedPreferences 产生的数据(实例代码)
2023-07-06 15:48:52
Maven添加Tomcat插件实现热部署代码实例
2021-12-09 02:03:49
java HttpClient传输json格式的参数实例讲解
2023-08-08 13:21:26
java中Object类4种方法详细介绍
2023-11-03 16:06:12
![](https://img.aspxhome.com/file/2023/4/58824_0s.jpg)
Java Scanner类用法及nextLine()产生的换行符问题实例分析
2022-12-22 21:44:04