views:

76

answers:

2

My application need to run some scripts, and I must be sure that the administrator is running them... what is the best way doing it using C#?

+3  A: 

Using WindowsPrincipal:

public static bool IsAdministrator()
{
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
Nissim
Just a note that the above will not work if UAC is enabled in Vista or Win7; you'll need to pop up a UAC confirmation box and elevate permissions in that case.
MisterZimbu
+5  A: 
return new WindowsPrincipal(WindowsIdentity.GetCurrent())
    .IsInRole(WindowsBuiltInRole.Administrator);
Alex Reitbort
Dude... it's verbatim identical... I splitted mine into rows for better understanding (let me tell you a secret - putting it all in one line doesn't make it better... just decreases readability)
Nissim
@Nissim: Either extreme can be bad, but we need to judge on a case-by-case basis.
Steven Sudit
@Nissm: You both answered simultaneously, or near enough that 5 minutes after the fact you're both listed as having posted "5 minutes ago". There is no reason for you to attack Alex; we're not here to earn rep, we're here to help.
Randolpho