Home
Manage Your Code
Snippet: Run an executable Runas (C#)
Title: Run an executable Runas Language: C#
Description: Runas in .net Views: 210
Author: astle lara Date Added: 8/27/2008
Copy Code  
1Console.Write("Username: ");
2string user = Console.ReadLine();
3string[] userParts = user.Split('\\');
4        
5Console.Write("Password: ");
6SecureString password = GetPassword();
7
8try
9{
10    ProcessStartInfo psi = new ProcessStartInfo(args[0]);
11    psi.UseShellExecute = false;
12            
13    if(userParts.Length == 2)
14    {
15        psi.Domain = userParts[0];
16        psi.UserName = userParts[1];
17    }
18    else
19    {
20        psi.UserName = userParts[0];
21    }
22
23    psi.Password = password;
24
25    Process.Start(psi);
26}
27catch(Win32Exception e)
28{
29    Console.WriteLine("Error starting application");
30    Console.WriteLine(e.Message);
31} 
Notes
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.