/// <summary> /// Does the actual impersonation. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domain">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="loadUserProfile">if set to <c>true</c> [load user profile].</param> private void ImpersonateValidUser(string userName, string domain, string password, bool loadUserProfile) { this.profileHandle = IntPtr.Zero; this.userToken = IntPtr.Zero; WindowsIdentity tempWindowsIdentity = null; IntPtr token = IntPtr.Zero; ProfileInfo profileInfo = new ProfileInfo(); profileInfo.Size = Marshal.SizeOf(profileInfo.GetType()); profileInfo.Flags = 0x1; profileInfo.UserName = userName; profileInfo.ProfilePath = null; profileInfo.DefaultPath = null; profileInfo.PolicyPath = null; profileInfo.ServerName = domain; try { if (!RevertToSelf()) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (LogonUser(userName, domain, password, Logon32LogonInteractive, Logon32ProviderDefault, ref token) == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (DuplicateToken(token, 2, ref this.userToken) == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (loadUserProfile && !LoadUserProfile(this.userToken, ref profileInfo)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Save the handle for dispose this.profileHandle = profileInfo.Profile; using (tempWindowsIdentity = new WindowsIdentity(this.userToken)) { this.impersonationContext = tempWindowsIdentity.Impersonate(); } } finally { if (token != IntPtr.Zero) { CloseHandle(token); } } }