/// <summary> /// Logs the specified user on to the local computer /// </summary> /// <param name="userName">The userName of the user to be impersonated</param> /// <param name="domain">The domain of the user</param> /// <param name="password">The password of the user</param> /// <param name="loadUserProfile">Indicates whether to load user profile or not</param> private void LogOn(string userName, string domain, string password, bool loadUserProfile) { Logger.Instance.WriteMethodEntry(EventIdentifier.LogOnUserLogOn, "Domain: {0}. UserName: {1}. LoadProfile: {2}.", domain, userName, loadUserProfile); try { if (!NativeMethods.LogonUser(userName, domain, password, this.logonType, this.logonProvider, out this.primaryToken)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } if (!loadUserProfile) { return; } NativeMethods.PROFILEINFO profileInfo = new NativeMethods.PROFILEINFO(); profileInfo.dwSize = Marshal.SizeOf(profileInfo); profileInfo.lpUserName = userName; profileInfo.lpServerName = domain; profileInfo.dwFlags = NativeMethods.PI_NOUI; if (!NativeMethods.LoadUserProfile(this.Token, ref profileInfo) || profileInfo.hProfile == IntPtr.Zero) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } this.profileHandle = new SafeRegistryHandle(profileInfo.hProfile, true); } finally { Logger.Instance.WriteMethodExit(EventIdentifier.LogOnUserLogOn, "Domain: {0}. UserName: {1}. LoadProfile: {2}.", domain, userName, loadUserProfile); } }