I have an application that needs to detect whether or not it is running with elevated privileges or not. I currently have code set up like this:
static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole (WindowsBuiltInRole.Administrator);
}
This works to detect if a user is an administrator or not, but doesn't work if running as an administrator without elevation. (For example in vshost.exe).
How can I determine whether or not elevation is [already in force or] possible?
Here is a modified version of this answer to include things like the proper disposing of resources and handling of Domain Administrators.
Try this out:
In .net Framwork 4.5 I found another method that works for me. In relation to the following script that can be found here here (in German)
In C# it looks like this:
But in .net < 4.5 the
WindowsPrincipal
class does not contain theUserClaims
property and I found no way to get this information.(new answer six years after the question was asked)
Disclaimer: This is just something that happened to work on my particular OS with my particular settings with my particular user:
So when I run this "Run as administrator", the property
get
accessor returnstrue
. When running normally (even if my user "is" administrator, just not running this particular application "as administrator"), it returnsfalse
.This seems much simpler than many other answers.
I have no idea if there are cases where this fails.
PS! This also seems OK:
The CodePlex project UAChelper has code that checks on elevation in UserAccountControl.cpp
UserAccountControl::IsUserAdmin
, that checks if UAC is enabled and then checks if process is elevated.from the function:
Using
TokenElevationType
would work, but if you PInvokeCheckTokenMembership()
against the admin group SID, your code would also work when UAC is off and on 2000/XP/2003 and will also handle deny SID's.There is also a
IsUserAnAdmin()
function that does theCheckTokenMembership
check for you, but MSDN says it might not be there forever