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
        Environment.Exit(0); // if the argument "restarted" was set, exit to avoid infinite loop

Friday, May 6, 2011

Get Command Line Arguments

Generally programs in Windows can be called with various arguments, which are called command line arguments.
For example some programs can be called directly with the file which is to be opened.
In console applications this arguments are directly accessible as parameters of the function Main().
In Windows Forms Application they are not, but we can get them with the function Environment.GetCommandLineArgs(), which returns the command line arguments as an array of the stype string.
The following code reads-out the passed arguments at program start:

string[] CommandLineArgs = Environment.GetCommandLineArgs();

As you can see, as first parameter always path and name of the executing program is  set.