Because Windows Access control can be inherited, when a security object is moved from one location to another, its access control may be affected. In order to allow access control of a security object to keep the existing data without inheriting the control options of the target path because of path changes. You can use the objectsecurity. setaccessruleprotection method. Note that the objectsecurity type is in the system. Security. accesscontrol namespace, And the objectsecurity and setauditruleprotection Methods correspond to the system access control list (SACL ).
The setaccessruleprotection method has two bool parameters. The first bool specifies whether inheritance is prohibited. The second bool specifies whether to retain the inherited access control. Of course, if the first parameter is false (inheritance is allowed), the value of the second parameter can be omitted because it will always retain the inheritance.
Finally, we use code to demonstrate how to copy a file to another location and retain the inheritance option of the source file and disable the inheritance option of the target directory:
// + Using system. IO;
// + Using system. Security. accesscontrol;
Static void copy (string SRC, string DEST)
{
File. Copy (SRC, DEST );
Filesecurity SECURITY = file. getaccesscontrol (SRC );
// Settings: do not allow inheritance, retain existing inherited
Security. setaccessruleprotection (True, true );
File. setaccesscontrol (DEST, security );
}