DEV Community

Antidisestablishmentarianism
Antidisestablishmentarianism

Posted on • Updated on

Restarting (not starting) you C# application from itself with administrator privileges.

I recently came across a situation where I wanted to restart my program with administrator privileges if it was run with no parameters so the program could execute an install sequence.
I used the following code in a .NET 7.0 Console application...

using System.Diagnostics;
using System.Security.Principal;

class Stuff
{
    static void Install()
    {
        try
        {
            //check if we are running as administrator currently
            if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
            {
                //Start new process as administrator. Environment.ProcessPath is the path of what we are currently running.
                Process.Start(new ProcessStartInfo { FileName = Environment.ProcessPath, UseShellExecute = true, Verb = "runas" });

                //Exit current process
                Environment.Exit(0);
            }
        }
        //if user selects "no" from adminstrator request.
        catch
        {
            Console.WriteLine("Administrative rights are required for installing this application.\nPress any key to exit.");
            Console.ReadKey(true);
            Environment.Exit(0);
        }

        //Do stuff...

        Console.WriteLine("Install complete\nPress any key to exit\n");
        Console.ReadKey(true);
        Environment.Exit(0);
    }

    public static void Main(string[] args)
    {
        if (args.Length == 0)
            Install();
        else
        {
            //Do stuff...
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)