12
votes

I have an C#, .Net 4.6.1 Windows Forms Application running on Windows Server Platforms (2008 or higher) which requires to be "Run as Administrator". Elevated privileges are required because the application changes User Access Rights on various folders (underneath the IIS Default Web Site Root if that matters).

I have no luck in detecting if the application has been "Run as Administrator". If I start the application normally (that is not as Administrator) the following code

var isAdmin = WindowsIdentity.GetCurrent().Owner.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid);

returns true but the code which changes some User Access Rights on a Directory fails with a Insufficient Privileges Error.

If I run the application as administrator the above check also returns true, but the changing of User Access rights works just fine.

Other attempts I have made without success:

  • Using the GetTokenInformation method inside the advapi32.dll as suggested here
  • Adding a manifest file to the application where I set the requestedExecutionLevel to requireAdministrator

Thanks in advance for any help.

2
As a workaround you could just initially check, can you change access rights on specific folder and if not, notify the user about insufficient rights. Unfortunately I have no direct experience with this kind of code and cannot give helpful answer :( - Arvo
Thank you @Arvo. I implemented a similar workaround for now. Still would like to find an answer. - Mats
So what actually happened when you used the manifest? - Damien_The_Unbeliever
Do you want to know if the current user who is running the programm is an administrator or if the application got started with administrator privileges -> "Run as Administrator". Because currently you checking if the user is admin. - C0d1ngJammer
Duplicate? See this, eg - sq33G

2 Answers

2
votes

The following must work (I hope so; I have a Windows client and it's working with me).

var Identity = WindowsIdentity.GetCurrent();
var Principal = new WindowsPrincipal(Identity);
bool IsAdmin = Principal.IsInRole(WindowsBuiltInRole.Administrator);
2
votes

Try to change the permissions of a known folder and if there is an exception then you know the program has not been run as administrator.