private Impersonation(string domain, string username, string password, LogonType logonType)
        {
            IntPtr handle;
            var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, 0, out handle);
            if (!ok)
            {
                var errorCode = Marshal.GetLastWin32Error();
                throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
            }

            var profileInfo = new ProfileInfo();
            profileInfo.dwSize = Marshal.SizeOf(profileInfo);
            profileInfo.lpUserName = username;
            profileInfo.dwFlags = 1;

            ok = NativeMethods.LoadUserProfile(handle, ref profileInfo);
            if (ok == false)
            {
                var errorCode = Marshal.GetLastWin32Error();
                throw new ApplicationException(string.Format("Could not load profile. Error code {0}.", errorCode));
            }
            NativeMethods.UnloadUserProfile(handle, profileInfo.hProfile);

            _handle = new SafeTokenHandle(handle);
            _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());
        }
 public static extern bool LoadUserProfile(IntPtr hToken, ref ProfileInfo lpProfileInfo);