Saturday, May 7, 2011

Restart Application With Administrative Rights

In an older post I showed, how to provide a C# application with administrative rights. For this though a file, the application manifest file, was needed.
Responding to a reader's request I want to present a little trick, how to equip an application with code alone with this rights.
Necessary for this is the class System.Diagnostics, which can start a process with any arguments. So we let, if the application is started with normal rights, restart itself with administrative rights.
To avoid an infinite loop, we add a new command line argument to the call.
The following code should demonstrate this idea:

private void Form1_Load(object sender, EventArgs e)
{
    string[] CommandLineArgs = Environment.GetCommandLineArgs(); // read-out command line arguments
    if (CommandLineArgs.Length <= 1 || CommandLineArgs[1] != "restarted"// if the 2. argument (the 1. is always the file path) != restarted, the program has not been restarted yet
    {
        ProcessStartInfo ProcessInfo = new ProcessStartInfo(Application.ExecutablePath, "restarted"); // set process information, application path and "restarted"
        ProcessInfo.Verb = "runas"// command for exectution as administrator
        Process.Start(ProcessInfo); // start process with the desired isettings
    }
    else
        Environment.Exit(0); // if the argument "restarted" was set, exit to avoid infinite loop
}

No comments:

Post a Comment