using System.Runtime.InteropServices;
namespace Test
{
using DWORD = System.UInt32;
using PSECURITY_DESCRIPTOR = System.IntPtr;
public class Security
{
enum SECURITY_INFORMATION : int
{
DACL_SECURITY_INFORMATION = 4,
}
[DllImport("advapi32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetFileSecurity(
string lpszUsername,
SECURITY_INFORMATION info,
PSECURITY_DESCRIPTOR descriptor,
DWORD val2,
out uint length);
[DllImport("advapi32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetFileSecurity(string lpszUsername,
SECURITY_INFORMATION info, PSECURITY_DESCRIPTOR descriptor);
static public void CopyFileSecurity(string fileName,
string targetFileName)
{
uint dwLength = 0;
bool result = GetFileSecurity(fileName,
SECURITY_INFORMATION.DACL_SECURITY_INFORMATION,
IntPtr.Zero, 0, out dwLength);
int lastError = Marshal.GetLastWin32Error() ;
//Console.WriteLine(string.Format("Last Error = {0}", lastError));
if ( ( result || lastError == 0x7a) && dwLength > 0)
{
PSECURITY_DESCRIPTOR pSecurityDescriptor =
System.Runtime.InteropServices.Marshal.
AllocHGlobal((int) dwLength);
if (GetFileSecurity(fileName,
SECURITY_INFORMATION.DACL_SECURITY_INFORMATION,
pSecurityDescriptor, dwLength, out dwLength))
{
SetFileSecurity(targetFileName,
SECURITY_INFORMATION.DACL_SECURITY_INFORMATION,
pSecurityDescriptor);
}
System.Runtime.InteropServices.Marshal.FreeHGlobal
(pSecurityDescriptor);
}
}
}
}