Restart with Elevated Privileges

Programming C#

With this code snippet you can restart your application with full elevated privileges. This means that Windows UAC will pop up and will ask you if you want to run the programm as administrator.

using System;
using System.Linq;

namespace ConsoleAppRestartElevated
class Program
static ConsoleKeyInfo cki;

static void Main(string[] args)
cki = Console.ReadKey();

if (cki.Key == ConsoleKey.Enter)
while (cki.Key != ConsoleKey.Escape);

static void ShowHint()
Console.WriteLine("[RET] ... restart with elevated privileges");
Console.WriteLine("[ESC] ... exit");

static void RestartWithElevatedPrivileges()
string programpath =
new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;
// Or for Windows Forms:
// string programpath = System.Windows.Forms.Application.ExecutablePath;

string[] arguments = System.Environment.GetCommandLineArgs().Skip(1).ToArray(); // requires Linq

System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo
FileName = programpath,
UseShellExecute = true,
Verb = "runas",
Arguments = String.Join(" ", arguments)

System.Environment.Exit(0); // return code 0, change if required
// Or for Windows Forms:
// System.Windows.Forms.Application.Exit( );

When you hit cancel in the Windows UAC dialog the call to System.Diagnostics.Process.Start will raise an exception.

Notice that if you hit [ENTER] a second time the Windows UAC will not pop up again because we're already running with elevated privileges.