-1

I have a windows app and i use the following to check if running as admin:

    public static bool IsAdministrator()
    {
        var identity = WindowsIdentity.GetCurrent();
        var principal = new WindowsPrincipal(identity);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);            
    }

     if (!IsAdministrator())
     {
         AlrtBox.Show("Run as Admin");
     }

But if i set a shortcut to the .exe file and set untick the checkbox Run As Administrator, it still seems to run regardless if checked or unchecked. I guess i am checking if the user is admin on windows(which they are) , but not if the check box is checked.

I want to check if the app is run as admin , regardless of the user on windows. How can i do that ?

Karen-S
  • 21
  • 3
  • Not sure what you're asking. In what circumstances do you want to return 'IsAdministrator' as true or false? Administrator account? User has admin privileges? RunAs admin account? – stuartd Nov 26 '20 at 00:09
  • regardless of the user , even if they are admin. I want to make sure that the applicatione (.exe) is run as admin. Ie the checkbox in the Advanced Properties is checked to run as admin ? – Karen-S Nov 26 '20 at 00:11
  • Ah, OK. Well, one way would be try attempt to do something only an admin could - like try to write a harmless value to the HKLM section of the registry? – stuartd Nov 26 '20 at 00:18
  • Maybe it's better to just attempt the administrative action and handling failure rather than (improperly) checking if it is possible to execute it? – Ray Nov 26 '20 at 00:21
  • Your admin test looks right to me. If you don't want to set requireAdministrator in the manifest, you can shell execute "runas" to re-launch your process (https://stackoverflow.com/questions/2532769/how-to-start-a-process-as-administrator-mode-in-c-sharp). – Jeremy Lakeman Nov 26 '20 at 00:44

1 Answers1

0

If the program always needs to run as administrator, you can use an Application.manifest file.

How do I create/edit a Manifest file

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Tu deschizi eu inchid
  • 4,117
  • 3
  • 13
  • 24
  • can i some how do what the manifest file does in c# code ? – Karen-S Nov 26 '20 at 00:15
  • You add the Application.manifest file to your project. On menu, Project => Add New Item => Application Manifest File – Tu deschizi eu inchid Nov 26 '20 at 00:37
  • If you only want to check, then you can do something like @stuartd stated in the comments in the previous post, but rather than write a value to the registry, try writing a text file to %SystemRoot%\system32 (ex: C:\Windows\system32). Use exception handling (try-catch). If the write was successful, delete the file. – Tu deschizi eu inchid Nov 26 '20 at 00:48