Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Is Your App Running As Administrator?

4.81/5 (32 votes)
25 Jan 2011CPOL 66K  
How to make your app detect whether or not it's running in admin mode.
Once again, I was working on a future CodeProject article, and decided that I wanted to force one of the applications in the solution to be run in admin mode so that the processing in that application could be performed without interference from the UAC. Because the whole application needs to run in admin mode, and because there may be times when I might want to run several subsequent forms from the Main method, I put this code into the Main method so that the form(s) won't even run if the app isn't in admin mode. Doing it this way also keeps me from having to add special code to any form that might become the main form. Here's the main method, in all it's glory.

C#
using System.Security.Prinicipal;

[STAThread]
static void Main()
{
    try
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(identity);
        if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
        {
            MessageBox.Show("You must run this application as administrator. Terminating.");
            Application.Exit();
        }

        Application.Run(new FormMain());
    }
    catch (Exception ex)
    {
        if (ex != null) {}
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)