Detect if running as Administrator with or without

2019-01-02 15:09发布

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?

8条回答
高级女魔头
2楼-- · 2019-01-02 15:59

I think there is one more issue. I checked solutions provided by you and have to say that in the installation of Windows 7 and logged on as an admin the check does not work. Windows never returns information that process runs in an elevated mode. So the sequence:

if (IsUacEnabled)
    return IsProcessInElevatedMode();
return IsUserAdmin();

does not returns true when logged as an Administrator but the process has all privileges to perform system operations (e.g. stop system services). The working sequence is:

if (IsUserAdmin())
    return true;

if (IsUacEnabled)
    return IsProcessInElevatedMode();

return false;

You should first check if the process is run in Administrator context. Additional info:

IsUacEnabled() - checks if the UAC has been enabled in the system (Windows)
IsProcessInElevatedMode() - checks if the process is run in an elevated mode
IsUserAdmin() - checks if the current user has an Administrtor role

All of that methods has been described in previous posts.

查看更多
冷夜・残月
3楼-- · 2019-01-02 16:00

Using UACHelper nuget package: https://www.nuget.org/packages/UACHelper/

if (UACHelper.IsElevated)
    // something
else
    // something else

There are a lot of other properties that can be used to detect if the user is, in fact, an administrator, or if the process is running under UAC virtualization, or if the desktop owner is the process owner. (Run as from limited account)

Check the read me for more information.

查看更多
登录 后发表回答