栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#设置文件权限的方法

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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的源码:

/// 
 /// 表示用户的标识、访问掩码和访问控制类型(允许或拒绝)的组合。 对象还包含有关子对象如何继承规则以及如何传播继承的信息。
 /// 
 public abstract class AccessRule : AuthorizationRule
 {
  /// 
  /// 使用指定的值初始化  类的一个新实例。
  /// 
  /// 应用访问规则的标识。此参数必须是可以强制转换为  的对象。此规则的访问掩码。访问掩码是一个 32 位的匿名位集合,其含义是由每个集成器定义的。如果此规则继承自父容器,则为 true。访问规则的继承属性。继承的访问规则是否自动传播。如果  设置为 ,则将忽略传播标志。有效的访问控制类型。 参数的值不能强制转换为 ,或者  参数包含无效值。 参数的值为零,或者  参数包含无法识别的标志值。
  protected AccessRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type);
  /// 
  /// 获取与此  对象关联的  对象。
  /// 
  /// 
  /// 
  /// 与此  对象关联的  对象。
  /// 
  public AccessControlType AccessControlType { get; }
 }

      看来DotNet中实现文件权限设置的操作的类,现在提供几个具体的文件设置操作代码:

3.获取目录权限列表:

    /// 
    /// 获取目录权限列表
    /// 
    /// 目录的路径。
    /// 指示目录的权限列表
    public IList GetDirectoryPermission(string path)
    {
      try
      {
 if (!DirectoryExists(path))
   return null;

 IList result = new List();
 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.设置目录权限

    /// 
    ///设置目录权限
    /// 
    /// 目录的路径。
    /// 在目录上设置的权限。
    /// 指示是否在目录上应用权限的值。
    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.设置目录权限列表

  /// 
  /// 设置目录权限列表
  /// 
  /// 目录的路径。
  /// 在目录上设置的权限。
  /// 指示是否在目录上应用权限的值。
  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#设置文件权限的资料请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/121833.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号