我已经成功地用于访问文件的计算机上为下面的代码:
#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