我已經成功地用於訪問文件的計算機上爲下面的代碼:
#region imports
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string
lpszUsername, string lpszDomain, string lpszPassword,
int dwLogonType, int dwLogonProvider, ref
IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto,
SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle
);
[DllImport("advapi32.dll", CharSet = CharSet.Auto,
SetLastError = true)]
public extern static bool DuplicateToken(IntPtr
existingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr
duplicateTokenHandle);
#endregion
#region logon consts
// logon types
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NETWORK = 3;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
// logon providers
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_PROVIDER_WINNT50 = 3;
const int LOGON32_PROVIDER_WINNT40 = 2;
const int LOGON32_PROVIDER_WINNT35 = 1;
#endregion
,然後在部分簽約,只需使用:
IntPtr token = IntPtr.Zero;
bool isSuccess = LogonUser("username", "domain", "password",
LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT, ref token);
using (WindowsImpersonationContext person = new WindowsIdentity(token).Impersonate())
{
//do your thing
person.Undo();
}
正如你可能會看到, 「撤消()」將使您不再以該用戶的身份登錄。所以在你完成之前不要使用它。但不要忘記使用它!
+1這真的是唯一的方法。 – Nate 2010-03-29 22:00:59
我是否可以長時間保持「標記」變量,然後在使用相同標記的不同點處使用「使用/撤消()」塊?「 – JCCyC 2010-03-29 22:19:31
我這樣認爲是實際登錄的模擬。我使用的是一個返回WindowsImpersonationContext的「GetImpersonation()」,如上所示 – 2010-03-29 22:22:27