DEV Community

Antidisestablishmentarianism
Antidisestablishmentarianism

Posted on • Edited 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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more