Running Processes as a Different User

Before Whidbey, if you wanted to run code as a different user, you needed to use impersonation.  There was no easy solution for starting a new process and having it run with a different user's credentaials.  Probably the best solution in v1.0 and 1.1 of the framework was to P/Invoke out to CreateProcessWithLogonW, which required creating a P/Invoke signature and dealing with unmanaged interop.

The Process class in Whidbey provides a mechanism which allows you to specify the user context that the new process should run under.  This is exposed through three new properties on the ProcessStartInfo class, Domain, UserName, and Password.  UserName and Domain are exactly what you would expect, strings representing the user to log on, and the domain that the user is a member of.

Creating a process as a different user is also one of the first uses of the new SecureString feature, since the Password property is a SecureString.  In order for this to work, you need to make sure that you're not using ShellExecute by setting the UseShellExecute property of the ProcessStartInfo object to false.

Here's some sample code that acts as a very basic RunAs command.  The GetPassword function can be found in my posting about SecureString.

Console.Write("Username: ");
string user = Console.ReadLine();
string[] userParts = user.Split('\\');
        
Console.Write("Password: ");
SecureString password = GetPassword();

try
{
    ProcessStartInfo psi = new ProcessStartInfo(args[0]);
    psi.UseShellExecute = false;
            
    if(userParts.Length == 2)
    {
        psi.Domain = userParts[0];
        psi.UserName = userParts[1];
    }
    else
    {
        psi.UserName = userParts[0];
    }

    psi.Password = password;

    Process.Start(psi);
}
catch(Win32Exception e)
{
    Console.WriteLine("Error starting application");
    Console.WriteLine(e.Message);
}