Source Address: http://www.cnblogs.com/rootkits/articles/1881101.html
In fact, all the operations and programming in. NET have become very simple and clear. If you want to add a file or folder to access the user and Set permissions for it, it is very complicated to implement in C ++. At the same time, it is necessary to call those annoying API functions. But it is different in. NET, because. NET uses a lot of encapsulated classes. In fact, the encapsulation class has encapsulated the system's API functions to solve the problem of programmers at the application layer.
The following is the C # implementation. Written in Visual Studio 2010 and tested in WIN 7.
1. File
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); // take full control as an Example
Dirinfo. SetAccessControl (fileSecurity );
}
2. Folder
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;
}
Example: string path = Server. MapPath ("~ /Model/Organization/xml "). Trim (); // remember to remove Spaces
// Set the xml folder read/write tobey2011-02-18 add
SetFolderACLInfo. SetFolderACL (path, "Everyone", System. Security. AccessControl. FileSystemRights. FullControl, System. Security. AccessControl. AccessControlType. Allow );