C#: Programmatically “Run As Administrator”

A few days ago I wanted to write to hosts, a HOSTS file in system32 used by Microsoft TCP/IP for Windows. Since this file is protected, you can edit it in administrative mode only. This means the user has to right click it and select “Run as administrator” for your project to run correctly. Fortunately there is a solution. The following code will request admin access from the user, and rerun it’s self in admin mode:

WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);

if (!administrativeMode) {
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.Verb = "runas";
    startInfo.FileName = Assembly.GetExecutingAssembly().CodeBase;
    try {
        Process.Start(startInfo);
        Application.Exit();
    }
    catch {
        //User denied access
        return;
    }
    return;
}
Advertisements

4 thoughts on “C#: Programmatically “Run As Administrator”

  1. can not use process.start() without paremeter. if i use it with Process.Start(startInfo); this i get two programs. i have tried couple of methods but could not able to solve it. Can you help me?

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s