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);
}
}
以上是对文件权限设置操作的一个简单介绍。
C#设置文件权限的更多相关文章
- mac设置文件权限问题
在使用mac时,经常我们遇到相关文件不能使用的情况,其实大多数情况都是,文件权限问题. 文件或目录的访问权限分为只读,只写和可执行三种.以文件为例,只读权限表示只允许读其内容,而禁止对其做任何的更改操 ...
- Java设置文件权限
今天遇到一个问题: java写的API,ppt转图片生成的目录及文件 在使用php调用API完成后,再使用php进行删除时,遇到了删除失败的问题(php删除的部分 查看) 部署的环境是Ubuntu ...
- day10设置文件权限
day10设置文件权限 yum复习 1.修改IP [root@localhost ~]# sed -i 's#.200#.50#g' /etc/sysconfig/network-scripts/if ...
- CentOS 7 使用 ACL 设置文件权限
Linux 系统标准的 ugo/rwx 集合并不允许为不同的用户配置不同的权限,所以 ACL 便被引入了进来,为的是为文件和目录定义更加详细的访问权限,而不仅仅是这些特别指定的特定权限. ACL 可 ...
- Linux设置文件权限和归属
前言:在Linux文件系统的安全模型中,为系统中的文件(或目录)赋予了两个属性:访问权限和文件所有者,简称为“权限”和“归属”.其中,访问权限包括读取.写入.可执行三种基本类型,归属包括属主(拥有该文 ...
- Linux下设置文件权限
文件权限示意图: 第一步:在终端创建用户 增加用户 useradd 用户名 设置密码 passwd 用户名 通过上述两条命令创建a1,a2两个用户. 第二步:在根目录使用管理员账号创建一个文件 在使用 ...
- ubuntu中chown设置文件权限
参考文献: http://yanwen.org/doc/chown.html http://www.cppblog.com/deercoder/articles/110129.html 可以通过ls ...
- linux 批量设置文件夹755 文件644权限
linux 批量设置文件夹755 文件644权限 文件来源 http://www.111cn.net/sys/linux/109724.htm 本文章来为各位介绍一篇关于linux 批量设置文件夹75 ...
- Shell文件权限和脚本执行
一.预备知识 1.shell的作用 2.常识 (1)Tab键自动补全 使用Terminal时,输入命令的前几个字母,敲tab会自动补全命令或文件名.目录等. 好处:操作速度更快:不容易出错: ...
随机推荐
- php面试 1013总结
面试题1:http://www.docin.com/p-288430879.html 数据库优化: session和cookies区别 缓存系统有哪些 myisam和InDB读写区别 varchar和 ...
- 【图文教程】Eclipse for PHP+XAMPP调试配置
一.下载安装XAMPP 下载地址:https://www.apachefriends.org/download.html, 一路“Next”,安装完毕. 二.下载Eclipse for PHP 下载地 ...
- Window.focus()让页面成为当前窗体
Window.focus()让页面成为当前窗体 最近在弄在线客服的时候,想在收到信息时候让窗体自动弹出到最前,最小化的时候也是弹出到最前.本来以为很麻烦,问了好多人,都不知道,在网上查资料也没有查到. ...
- OstrichNet 简易统计信息收集工具
Ostrich 是twitter用于监控服务器性能的一个scala库,项目地址https://github.com/twitter/ostrich, 主要功能是收集.展示统计信息, 同时也提供了关闭服 ...
- ASP.NET MVC学前篇之扩展方法、链式编程
ASP.NET MVC学前篇之扩展方法.链式编程 前言 目的没有别的,就是介绍几点在ASP.NETMVC 用到C#语言特性,还有一些其他琐碎的知识点,强行的划分一个范围的话,只能说都跟MVC有关,有的 ...
- WCF basicHttpBinding之Transport Security Mode, clientCredentialType="None"
原创地址:http://www.cnblogs.com/jfzhu/p/4071342.html 转载请注明出处 前面文章介绍了<WCF basicHttpBinding之Message Sec ...
- RAID 概述
原创地址:http://www.cnblogs.com/jfzhu/p/3999283.html 转载请注明出处 独立硬盘冗余阵列(RAID, Redundant Array of Indep ...
- C语言 · 图形显示
问题描述 编写一个程序,首先输入一个整数,例如5,然后在屏幕上显示如下的图形(5表示行数): * * * * * * * * * * * * * * * #include "stdi ...
- Redis应用场景一
Redis开创了一种新的数据存储思路,使用Redis,我们不用在面对功能单调的数据库时,把精力放在如何把大象放进冰箱这样的问题上,而是利用Redis灵活多变的数据结构和数据操作,为不同的大象构建不同的 ...
- vue.js组件化开发实践
前言 公司目前制作一个H5活动,特别是有一定统一结构的活动,都要码一个重复的轮子.后来接到一个基于模板的活动设计系统的需求,便有了下面的内容.借油开车. 组件化 需求一到,接就是怎么实现,技术选型自然 ...