How to start a Process as administrator mode in C#
Long back I wrote a post on how to create UAC Compatible applications in .NET. In that UAC will be applicable for the whole application. Today I got a scenario like I want to install a Windows service from my application, but I don’t want to enable UAC for the whole application. I am using the Process.Start() method for invoking the sc.exe. As I am not running that application as Administrator, I was getting an Access Denied message. Then I figured out the solution with Verb property of ProcessStartInfo. Simply set the Verb property of ProcessStartInfo as “runas”, this will popup the UAC dialog, before starting the application. If the user press Yes, it will launch the application otherwise it will throw a WIN32Exception.
var processStartInfo = new ProcessStartInfo(@"C:\Windows\Notepad.exe");
processStartInfo.Verb = "runas";
try
{
Process.Start(processStartInfo);
}
catch (Win32Exception ex)
{
MessageBox.Show(ex.ToString(), "Run As",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
You can also check the OS platform also, this is required only if you are using Vista or Windows 7. You can check this using Environment.OSVersion.Version.Major, if it is more than 6, it is Vista or above.
if (Environment.OSVersion.Version.Major >= 6)
{
processStartInfo.Verb = "runas";
}
Happy Programming