在开发中,我们经常会使用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);
}
}

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

C#设置文件权限的更多相关文章

  1. mac设置文件权限问题

    在使用mac时,经常我们遇到相关文件不能使用的情况,其实大多数情况都是,文件权限问题. 文件或目录的访问权限分为只读,只写和可执行三种.以文件为例,只读权限表示只允许读其内容,而禁止对其做任何的更改操 ...

  2. Java设置文件权限

    今天遇到一个问题: java写的API,ppt转图片生成的目录及文件 在使用php调用API完成后,再使用php进行删除时,遇到了删除失败的问题(php删除的部分  查看) 部署的环境是Ubuntu ...

  3. day10设置文件权限

    day10设置文件权限 yum复习 1.修改IP [root@localhost ~]# sed -i 's#.200#.50#g' /etc/sysconfig/network-scripts/if ...

  4. CentOS 7 使用 ACL 设置文件权限

    Linux  系统标准的 ugo/rwx 集合并不允许为不同的用户配置不同的权限,所以 ACL 便被引入了进来,为的是为文件和目录定义更加详细的访问权限,而不仅仅是这些特别指定的特定权限. ACL 可 ...

  5. Linux设置文件权限和归属

    前言:在Linux文件系统的安全模型中,为系统中的文件(或目录)赋予了两个属性:访问权限和文件所有者,简称为“权限”和“归属”.其中,访问权限包括读取.写入.可执行三种基本类型,归属包括属主(拥有该文 ...

  6. Linux下设置文件权限

    文件权限示意图: 第一步:在终端创建用户 增加用户 useradd 用户名 设置密码 passwd 用户名 通过上述两条命令创建a1,a2两个用户. 第二步:在根目录使用管理员账号创建一个文件 在使用 ...

  7. ubuntu中chown设置文件权限

    参考文献: http://yanwen.org/doc/chown.html http://www.cppblog.com/deercoder/articles/110129.html 可以通过ls ...

  8. linux 批量设置文件夹755 文件644权限

    linux 批量设置文件夹755 文件644权限 文件来源 http://www.111cn.net/sys/linux/109724.htm 本文章来为各位介绍一篇关于linux 批量设置文件夹75 ...

  9. Shell文件权限和脚本执行

    一.预备知识 1.shell的作用   2.常识 (1)Tab键自动补全   使用Terminal时,输入命令的前几个字母,敲tab会自动补全命令或文件名.目录等. 好处:操作速度更快:不容易出错: ...

随机推荐

  1. Window平台Grmon下如何使用gdb进行调试

    Window平台Grmon下如何使用gdb进行调试 1输入cmd命令,打开其窗口,进入你要执行的文件目录下 2.连接开发板,输入grmon –altjtag –u 3.连上后,输入gdb命令 4.再输 ...

  2. Webpack教程

    打开链接:Webpack教程

  3. Windows和Linux都有的Copy-on-write技术

    Windows和Linux都有的Copy-on-write技术 MySQL技术内幕Innodb存储引擎第2版 P375 SQL Server2008 实现与维护(MCTS教程)P199 LVM快照技术 ...

  4. 剑指Offer面试题:31.两个链表的第一个公共节点

    一.题目:两个链表的第一个公共节点 题目:输入两个链表,找出它们的第一个公共结点. 链表结点定义如下,这里使用C#语言描述: public class Node { public int key; p ...

  5. 走向面试之数据库基础:三、SQL进阶之变量、事务、存储过程与触发器

    一.变量那点事儿 1.1 局部变量 (1)声明局部变量 DECLARE @变量名 数据类型 ) DECLARE @id int (2)为变量赋值 SET @变量名 =值 --set用于普通的赋值 SE ...

  6. ASP.Net MVC开发基础学习笔记:二、HtmlHelper与扩展方法

    一.一个功能强大的页面开发辅助类—HtmlHelper初步了解 1.1 有失必有得 在ASP.Net MVC中微软并没有提供类似服务器端控件那种开发方式,毕竟微软的MVC就是传统的请求处理响应的回归. ...

  7. [.net 面向对象程序设计深入](1)UML——在Visual Studio 2013/2015中设计UML类图

    [.net 面向对象程序设计深入](1)UML——在Visual Studio 2013/2015中设计UML类图 1.UML简介 Unified Modeling Language (UML)又称统 ...

  8. 图片拾取器-PicPicker

    最近报名参加了360前端星计划,想当一名前端实习生,学习更多更流行的前端知识.然后需要完成一个作业,才能进培训,进了培训还得看运气才能留下,流程不少.书归正传,请看: 课后作业题目 请从下面两个题目中 ...

  9. 前nginx后Apache+Node反向代理

    前几天一直在被一个问题困扰,机器上跑的站点太多了,Apache上面有十几个,NodeJS的也有一堆,记端口号都要烦死,于是萌生了使用反向代理的想法.出发点貌似太low了,完全不是出于负载均衡.高并发什 ...

  10. Ubuntu安装Python2.7,nodejs

    安装Python2.7 sudo add-apt-repository ppa:fkrull/deadsnakes-python2.7sudo apt-get update sudo apt-get ...