Impersonate() public static method

Impersonates the specified user within the Explorer process context.
Explorer process is vital for the system and should always be there, if the user is logged in.
is or empty. is not in the DOMAIN\username format. /// No processes are running for the . /// -or- /// Process handle cannot be duplicated. ///
public static Impersonate ( string domainUser ) : System.Security.Principal.WindowsImpersonationContext
domainUser string The domain user.
return System.Security.Principal.WindowsImpersonationContext
Exemplo n.º 1
0
        /// <summary>
        /// Impersonates the currently logged on user in the current thread context.
        /// </summary>
        /// <returns>Impersonation context.</returns>
        public static WindowsImpersonationContext ImpersonateCurrentUser()
        {
            try
            {
                return(Impersonator.Impersonate(UserHelper.LoggedOnUser));
            }
            catch
            {
                // Exception might occur, if we have outdated username information.
                // Maybe, that user has logged out. So, try to find a new username.
                string previousUserName = UserHelper.LoggedOnUser;
                string newUserName      = UserHelper.GetCurrentUser();

                // If username is the same, don't retry.
                if (string.Equals(previousUserName, newUserName, StringComparison.OrdinalIgnoreCase))
                {
                    throw;
                }

                UserHelper.LoggedOnUser = newUserName;
            }

            return(Impersonator.Impersonate(UserHelper.LoggedOnUser));
        }
Exemplo n.º 2
0
 /// <summary>
 /// Impersonates the specified user within the <c>Explorer</c> process context.<br/>
 /// <c>Explorer</c> process is vital for the system and should always be there, if the user is logged in.
 /// </summary>
 /// <param name="domainUser">The domain user.</param>
 /// <returns>
 /// Impersonated context.
 /// </returns>
 /// <exception cref="ArgumentNullException"><paramref name="domainUser"/> is <see langword="null"/> or empty.</exception>
 /// <exception cref="ArgumentException"><paramref name="domainUser"/> is not in the <c>DOMAIN\username</c> format.</exception>
 /// <exception cref="InvalidOperationException">
 /// No processes are running for the <paramref name="domainUser"/>.
 ///     <para>-or-</para>
 /// Process handle cannot be duplicated.
 /// </exception>
 /// <seealso cref="Impersonate(string,Predicate{Process})"/>
 public static WindowsImpersonationContext Impersonate(string domainUser)
 {
     return(Impersonator.Impersonate(domainUser, p => p.ProcessName.Equals("explorer", StringComparison.OrdinalIgnoreCase)));
 }