I want to know if a program is running as administrator.
The user doesn't have to be administrator. I only want to know if my application has rights to edit some secured files that are editable when running as Administrator.
I want to know if a program is running as administrator.
The user doesn't have to be administrator. I only want to know if my application has rights to edit some secured files that are editable when running as Administrator.
This will return a bool valid
using System.Security.Principal;
bool isElevated;
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
Here's @atrljoe's answer turned into a one liner using the latest C#:
using System.Security.Principal;
static bool IsElevated => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
Dispose
as you are required by contract to do –
Bedpan To avoid SecurityException
, and leaks, like not closing WindowsIdentity.GetCurrent()
, since WindowsPrincipal
does not explicitly close, but only creates a new connection and only then closes it.
private static bool IsAdministrationRules() {
try {
using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) {
return (new WindowsPrincipal(identity)).IsInRole(WindowsBuiltInRole.Administrator);
}
} catch {
return false;
}
}
© 2022 - 2024 — McMap. All rights reserved.