0

其实在.NET中一切的操作和编程变的非常的简单而明了。如想要添加一个文件或文件夹访问用户并为其设置权限的话,如果在C++中实现则非常的复杂。并同时要调用那些烦人的API函数才能完成。但在.NET中则不同,因为.NET中用了很多已封装的类来完成。其实封装类的内部已经封装了系统的API函数从而解决了应用层的编程者。

  以下是C#实现。用Visual Studio 2010编写,在WIN 7中测试通过。

  1、文件

  static void Main(string[] args)        

  {            

    SetAccount(@"C:\eee.txt", "BATCH");
        Console.WriteLine("OK");
        Console.Read();        

  } 

  public static void SetAccount(string filePath, string username)        

  {           

    FileInfo fileInfo = new FileInfo(filePath); 

    FileSecurity fileSecurity = fileInfo.GetAccessControl();     

    fileSecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl, AccessControlType.Allow));     //以完全控制为例

    fileInfo.SetAccessControl(fileSecurity );        

  }

  2、文件夹

  public static void Main()        

  {            

    SetFolderACL("C:\\test", "BATCH", FileSystemRights.FullControl, AccessControlType.Allow);        

  }        

  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;        

  }

例子: string path = Server.MapPath("~/Model/Organization/xml").Trim();//记得去空格
            //设置xml文件夹可读写 tobey2011-02-18 add
            SetFolderACLInfo.SetFolderACL(path, "Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);

关闭 返回顶部
联系我们
Copyright © 2011. 聚财吧. All rights reserved.