源地址:http://www.cnblogs.com/rootkits/articles/1881101.html
其實在.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();
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl, AccessControlType.Allow)); //以完全控製為例
dirinfo.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);