服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - 采用C#代码动态设置文件权限

采用C#代码动态设置文件权限

2021-12-13 15:09彭泽0902 C#

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

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

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

    1.现在看一下FileSystemAccessRule的实现代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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的源码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/// <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.获取目录权限列表:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/// <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.设置目录权限

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/// <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.设置目录权限列表

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/// <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);
  }
 }

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

以上就是本文的全部内容,希望对大家有所帮助,同时也希望多多支持服务器之家!

原文链接:http://www.cnblogs.com/pengze0902/p/5988595.html

 

延伸 · 阅读

精彩推荐
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03