以下方法在 Win7 Pro SP1 x64 上运行良好,但是当我在 Win7 Pro SP1 x86 上运行它时,它在到达 //write the new owner 注释时失败
为什么它适用于一个而不适用于另一个的一些原因是什么?
这是使用 pinvoke
谢谢!
public static void ChangeOwner(ref string strPath, string strUserName)
{
IntPtr pNewOwner = default(IntPtr);
IntPtr deUse = default(IntPtr);
Win32Exception Win32Error = default(Win32Exception);
string domain_name = null;
int ret = 0;
int sid_len = 0;
int domain_len = 0;
// Series of quick sanity checks before we proceed...
//Do we have the required Privilege?
if (SetPrivileges() == false)
{
throw new Exception("Required privilege not held by the user");
}
// Convert the name to a valid SID
sid_len = SID_SIZE;
pNewOwner = Marshal.AllocHGlobal(sid_len);
domain_len = NAME_SIZE;
string domainThing = "";
domain_name = domainThing.PadRight(domain_len);
if (LookupAccountName(null, strUserName, pNewOwner, ref sid_len, domain_name, ref domain_len, ref deUse) == false)
{
ret = Marshal.GetLastWin32Error();
Win32Error = new Win32Exception(ret);
//throw new Exception(Win32Error.Message);
}
// write the new Owner
ret = SetNamedSecurityInfo(strPath, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, pNewOwner, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if (ret != 0)
{
Win32Error = new Win32Exception(ret);
throw new Exception(Win32Error.Message);
}
// clean up and go home
Marshal.FreeHGlobal(pNewOwner);
}