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

来源:互联网 发布:js 正则 编辑:程序博客网 时间:2024/05/06 03:43

http://blog.csdn.net/hz932/archive/2008/07/12/2644097.aspx

 

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

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

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

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

view plaincopy to clipboardprint?
  1.   
  2. using System;   
  3. using System.Collections;   
  4. using System.Text;   
  5. using System.Security.AccessControl;   
  6. using System.IO;  
view plaincopy to clipboardprint?
  1. namespace ACL   
  2. {   
  3.  class ACL_FS   
  4.  { //By 同济黄正 <A href="http://hz932.ys168.com">http://hz932.ys168.com</A>   
  5.   public static bool SetFolderACL(String FolderPath , String UserName , FileSystemRights Rights , AccessControlType AllowOrDeny)   
  6.   {   
  7.    InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;   
  8.    return SetFolderACL(FolderPath , UserName , Rights , AllowOrDeny , inherits , PropagationFlags.None , AccessControlModification.Add);   
  9.   }  
view plaincopy to clipboardprint?
  1.   public static bool SetFolderACL(String FolderPath , String UserName , FileSystemRights Rights , AccessControlType AllowOrDeny   
  2.    , InheritanceFlags Inherits , PropagationFlags PropagateToChildren , AccessControlModification AddResetOrRemove)   
  3.   {   
  4.    //过程:获取文件夹安全对象、构造访问规则、修改安全对象的访问规则、重新设置文件夹安全对象   
  5.    bool ret;   
  6.    DirectoryInfo folder = new DirectoryInfo(FolderPath);   
  7.    DirectorySecurity dSecurity = folder.GetAccessControl(AccessControlSections.All);   
  8.    FileSystemAccessRule accRule = new FileSystemAccessRule(UserName , Rights , Inherits , PropagateToChildren , AllowOrDeny);   
  9.    dSecurity.ModifyAccessRule(AddResetOrRemove , accRule , out ret);   
  10.    folder.SetAccessControl(dSecurity);   
  11.    return ret;   
  12.   }  
view plaincopy to clipboardprint?
  1.   /// <returns>String,FileSystemRights键值对</returns>   
  2.   public static Hashtable GetACL(String FolderPath)   
  3.   {   
  4.    Hashtable ret = new Hashtable();   
  5.    DirectorySecurity sec = Directory.GetAccessControl(FolderPath , AccessControlSections.All);   
  6.    foreach (FileSystemAccessRule rule in sec.GetAccessRules(true , true , typeof(System.Security.Principal.NTAccount)))   
  7.    {   
  8.     ret[rule.IdentityReference.ToString()] = rule.FileSystemRights;   
  9.    }   
  10.    return ret;   
  11.   }   
  12.   public static string GetACLString(String FolderPath)   
  13.   {   
  14.    StringBuilder sb = new StringBuilder();   
  15.    Hashtable rights=GetACL(FolderPath);   
  16.    foreach (string key in rights.Keys)   
  17.    {   
  18.     sb.Append(key + ":/t" + ((FileSystemRights)rights[key]).ToString()+"/r/n");   
  19.    }   
  20.    return sb.ToString();   
  21.   }  
view plaincopy to clipboardprint?
  1.  }   
  2. }   
  3. //以上在WindowsXP、Windows Server 2003下测试通过。