C#设置文件权限的方法
作者:彭泽0902 发布时间:2022-08-31 22:35:42
标签:c#,设置,文件,权限
在开发中,我们经常会使用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
0
投稿
猜你喜欢
- 最近有个粉丝提了个问题,说他在Spring Security中用JWT做退出登录的时无法获取当前用户,导致无法证明“我就是要退出的那个我”,
- 验证码逻辑以前在项目中也做过验证码,生成验证码的代码网上有很多,也有一些第三方的jar包也可以生成漂亮的验证码。验证码逻辑很简单,就是在登录
- mybatis insert foreach循环插入@Insert("<script>" +
- 一、文件存储特点:openFileInput()和openFileOutput()读取设备上的文件。优点:适用于存储大量的数据,可以存储图片
- 本文由Markdown语法编辑器编辑完成。1. 需求分析;已知当在调用某一webservice的服务时,如果调用成功,会接受到该服务的返回X
- 一、@ConditionalOnClass() Spring中存在指定class对象时,注入指定配置和ConditionalOnBean()
- AsyncTask什么是AsyncTaskAsyncTask是一个轻量级的异步任务类,它可以在线程池中执行后台任务,然后把执行的进度和结果传
- 介绍该系统有三个角色,分别是:普通用户、房屋中介、管理员。普通用户的功能:浏览房屋信息、预约看房、和中介聊天、申请成为中介等等。房屋中介的功
- Reflections通过扫描classpath,索引元数据,并且允许在运行时查询这些元数据。使用Reflections可以很轻松的获取以下
- 一、访问控制url匹配在前面讲解了认证中所有常用配置,主要是对http.formLogin()进行操作。而在配置类中 http.author
- package TestList;import java.util.ArrayList;import java.util.Iterator;
- APP生命周期wpf项目目录中有一个App.xaml.cs文件,该文件中App是一个partical类,与之对应的另一partical部分在
- 文章主要涉及到以下几个问题:怎么实现Java的序列化为什么实现了java.io.Serializable接口才能被序列化transient的
- 报文(message)是网络中交换与传输的数据单元,即站点一次性要发送的数据块。报文包含了将要发送的完整的数据信息,其长短很不一致,长度不限
- 改了个bug,发现这个东西以前不知道,搜索了一下,看到的都是长篇大论,还谈js的源码,也是醉了。我就简单的说说这个是干啥的。简单说:就是触发
- 第一种查看防火墙是否打开6379端口 查看防火墙状态systemctl status firewalld如果防火墙没有启动的话。可以选择直接
- Java是一门面向对象的语言,即一切皆是对象!那么为何数据类型中还分为:基本类型和对象?Java中有8种基本数据类型boolean、byte
- 写在前面关于数据结构,Java官方其实已经帮我们写好并封装起来了,在真正需要使用的时候直接调用即可,但为了更好的理解数据结构,我会按照源码的
- 目标效果: 点击动画按钮之后每张牌各自旋转 散开到屏幕上半部分的任意位置之后回到初始位置 比较像LOL男刀的技能动画 : )1: 创建卡牌对
- 1.构造器也就是在上一篇讲的那个例子,调用默认的无参构造函数2.静态工厂方法1)创建需要执行的方法的类public class HelloW