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#设置文件权限的方法的详细内容,更多关于C#设置文件权限的资料请关注我们其它相关文章!

(0)

相关推荐

  • c#添加图片、文本水印到PDF文件

    概述 一般我们在向文档添加水印时,会分为直接添加文字水印和加载图片添加图片水印两种情况.常见的,在添加文字水印时会多以声明文档版权.权威性的文字.标语或者名称等:同样的,图片水印也通常可以是某组织的LOGO.印章.或者其他能够指示性的图片等.在下面的文档中,将介绍通过C#编程来添加PDF水印的方法,包括: 1 添加文本水印 2 添加图片水印 使用工具 Spire.PDF for .NET C#代码示例(供参考) [示例1]添加PDF文本水印 using Spire.Pdf; using Spir

  • C# http系列之以form-data方式上传多个文件及键值对集合到远程服务器

    系列目录 [已更新最新开发文章,点击查看详细] 类似于以下场景,将表单中的用户信息(包含附件)上传到服务器并保存到数据库中, <form id="form1" runat="server" action="UserManageHandler.ashx" method="post" enctype="multipart/form-data"> <div> 名称: <input t

  • C# 读写XML文件实例代码

    C#史上最简单读写xml文件方式,创建控制台应用程序赋值代码,就可以运行,需要改动,请自行调整 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace ConsoleApp1 { class Program { public cons

  • C#锁住文件的操作步骤

    我们有时用C#需要实现锁住文件的功能,该如何锁住文件呢?下面小编给大家介绍一下. 首先大家需要到码云里面找到如下图所示的文件锁的项目,如下图所示 下载下来以后导入到Visual Studio中,如下图所示,这个项目是用C#写的,所以你可以直接阅读的 接着运行这个C#项目,就可以看到如下图所示的加索界面 我们将要加锁的文件拖入到正方形区域,如下图所示 然后你就会看到文件被锁住了,缩略图变成了一把锁,而且不能点击了,如下图所示 接着如果想解锁也是将加锁的文件拖入到界面中,如下图所示 最后提示解锁成功

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

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

  • c# 用Base64实现文件上传

    Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,它是一种基于64个可打印字符来表示二进制数据的方法. 使用base64进行文件上传的具体流程是:前台使用js将文件转换为base64格式,后台通过高级编程语言,将base64格式的文件,转换为原文件.下面就来演示一下,C#语言配合js,如何实现图片的base64格式上传与解析保存.     首先看一下前台是如何将文件读取到的,请先看如下js代码: var DataforUp = ""; var reader = new

  • C# protobuf自动更新cs文件

    网上的教程大都是手动通过protoc编译, 比较难用 给当前工程添加"Google.Protobuf"和"Grpc.Tools"的引用(通过nuget), 然后添加proto文件, 编辑.csproj文件 <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework>

  • C#中将xml文件反序列化为实例时采用基类还是派生类的知识点讨论

    基类: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DeserializeTest { public class SettingsBase { private string m_fileName; public string FileName { get { return m_fileName; } set { m_fileName = value;

  • C# 监控 Windows 文件夹的方法

    您是否为无法看到孩子在电脑上存储的图片而发愁,您是否为无法监控员工在电脑上存储的东西而发愁,那么今天给您推荐的这款产品绝对是您不二的选择,它是由美国大厂生产,完全符合国际标准的产品,完美支持 Windows 98 以上系统,他就是 FileSystemWatcher 牌监控仪.他会侦听文件系统更改通知,并在目录或目录中的文件更改时引发事件.下面我们就来看看他的细节. 零.细节特征 1.常用的方法有: OnChanged(FileSystemEventArgs) 当更改被监控目录中文件或目录的大小

  • c# 实现文件上传下载功能的实例代码

    NuGet 安装SqlSugar 1.Model文件下新建 DbContext 类 public class DbContext { public DbContext() { Db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = "server=localhost;uid=root;pwd=woshishui;database=test", DbType = DbType.MySql, InitKeyTy

  • C#拷贝整个文件夹及子目录和其中文件的方法

    下面一段代码给大家介绍C#拷贝整个文件夹以及子目录和其中文件,具体代码如下所示: private void CopyDirectory( string srcPath, string desPath) { string folderName = srcdir.Substring(srcdir.LastIndexOf( "\\" )+1); string desfolderdir = desPath + "\\" + folderName; if (desdir.La

随机推荐