完成此操作如果您作为服务运行,则可能需要模拟。这是不完整的代码,但它的要点:
[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)]
private static extern unsafe int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref string lpBuffer, int nSize, IntPtr* arguments);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);
IntPtr token = IntPtr.Zero;
bool isSuccess = LogonUser(username, domain, password, impersonationType, Logon32ProviderDefault, ref token);
if (!isSuccess)
{
RaiseLastError();
}
WindowsIdentity newIdentity = new WindowsIdentity(token);
WindowsImpersonationContext impersonatedUser = newIdentity.Impersonate();
保存令牌再后来
CloseHandle(token);
如果它是你可以在需要的用户帐户运行Windows服务。或者为此服务创建一个特殊帐户。 – Den 2010-10-26 14:50:01
@Den是的,你可以。这并不妨碍我提供替代方案。 – 2010-10-26 14:52:47