How to use C# to detect if user has administrative rights in Windows Vista?
Posted: (EET/GMT+2)
If you are developing applications for Windows Vista, you are surely aware of User Account Control or UAC. With UAC, even users that belong to the Administrators group are running Vista with standard user rights. But with a process called elevation, users can raise their rights to real administrators. Of course, the question is: how to detect is the user is running your application with real administrative rights, and isn't just a standard user beloning to the admin group? The code is quite simple, thanks to the extensive .NET base class libraries:
using System.Security.Principal;
using System.Threading;
public bool RunningAsAdministrator()
{
AppDomain.CurrentDomain.SetPrincipalPolicy(
PrincipalPolicy.WindowsPrincipal);
// read current identity for this thread
WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
WindowsIdentity identity = (WindowsIdentity)principal.Identity;
// can the Administrator role be found?
bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
return isAdmin;
}
Keywords: HowTo, RunningAsAdministrator, RunningAsAdmin, IsAdmin, .NET, C#, Visual Studio, Microsoft Windows Vista.