.Net下查看和修改文件夹的ACL安全权限(C#)

这是一个在.Net下修改文件夹或文件的ACL安全权限的类:

SetFolderACL:两个重载函数,设置权限的方法,根据需要选择重载。

GetACL: 查看文件夹权限的信息,用户名-权限键值对

GetACLString:查看文件夹权限的文本信息,用户名-权限名键值对

 



using System;
using System.Collections;
using System.Text;
using System.Security.AccessControl;
using System.IO;
namespace ACL
{
 class ACL_FS
 { //By 同济黄正 http://hz932.ys168.com
  public static bool SetFolderACL(String FolderPath , String UserName , FileSystemRights Rights , AccessControlType AllowOrDeny)
  {
   InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
   return SetFolderACL(FolderPath , UserName , Rights , AllowOrDeny , inherits , PropagationFlags.None , AccessControlModification.Add);
  }
  public static bool SetFolderACL(String FolderPath , String UserName , FileSystemRights Rights , AccessControlType AllowOrDeny
   , InheritanceFlags Inherits , PropagationFlags PropagateToChildren , AccessControlModification AddResetOrRemove)
  {
   //过程:获取文件夹安全对象、构造访问规则、修改安全对象的访问规则、重新设置文件夹安全对象
   bool ret;
   DirectoryInfo folder = new DirectoryInfo(FolderPath);
   DirectorySecurity dSecurity = folder.GetAccessControl(AccessControlSections.All);
   FileSystemAccessRule accRule = new FileSystemAccessRule(UserName , Rights , Inherits , PropagateToChildren , AllowOrDeny);
   dSecurity.ModifyAccessRule(AddResetOrRemove , accRule , out ret);
   folder.SetAccessControl(dSecurity);
   return ret;
  }
  /// <returns>String,FileSystemRights键值对</returns>
  public static Hashtable GetACL(String FolderPath)
  {
   Hashtable ret = new Hashtable();
   DirectorySecurity sec = Directory.GetAccessControl(FolderPath , AccessControlSections.All);
   foreach (FileSystemAccessRule rule in sec.GetAccessRules(true , true , typeof(System.Security.Principal.NTAccount)))
   {
    ret[rule.IdentityReference.ToString()] = rule.FileSystemRights;
   }
   return ret;
  }
  public static string GetACLString(String FolderPath)
  {
   StringBuilder sb = new StringBuilder();
   Hashtable rights=GetACL(FolderPath);
   foreach (string key in rights.Keys)
   {
    sb.Append(key + ":/t" + ((FileSystemRights)rights[key]).ToString()+"/r/n");
   }
   return sb.ToString();
  }
 }
}
//以上在WindowsXP、Windows Server 2003下测试通过。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值