2012-09-21

Run a process as the admin of the server

Some programs require to run as administrator in order to work properly. We can use the Process class in asp.net to run a process in server. The below example code shows, how to pass credentials to start the process when we use the Process class to start a process.

string returnvalue = string.Empty;

ProcessStartInfo info = new ProcessStartInfo(fileName);
info.UseShellExecute = false;

info.Arguments = args;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;

string passwordStr = "PasswordHere";

SecureString password = new SecureString();

foreach (char c in passwordStr)
   password.AppendChar(c);

info.Password = password;
info.UserName = "Administrator";

using (Process process = Process.Start(info))
{
     StreamReader sr = process.StandardOutput;
     returnvalue = sr.ReadToEnd();
}

We have to pass the Password as a SecureString. So, first we have to convert the string value to a SecureString by passing each character through a loop and append each to the SecureString. ProcessStartInfo class has the properties “UserName” and “Password” which we are setting to start the process with the given credentials.

3 comments:

Vishal Ranjan,Software Developer said...

Nice Article..

Lê Đức Sơn said...

I runing IIS6, but Error: Exception Details: System.ComponentModel.Win32Exception: Access is denied Please help me. thank you.

Ruchira Gamage said...

I'm sorry I've never tried it on IIS 6. See whether below solution can help you

http://stackoverflow.com/questions/13974653/system-componentmodel-win32exception-when-starting-process-file-not-found-but