This is pretty cool. A lot of the stuff that I write is low level admin type of utilities. As my coding meter moves further away from the Win32 Delphi to C#, I’ll need stuff like this more often.
Following, is the method that I use to determine if a user is an Administrator. Note that in .NET 1.0/1.1 the using construct wrapped around the creation of the WindowsIdentity won’t compile as its implementation of IDisposable is new for .NET 2.0. Previously you had to rely on the finalizer of the object to run so that the handle of the user token could be freed.using System;
public static bool IsAdministrator
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
WindowsPrincipal wp = new WindowsPrincipal(identity);
There is also a check to determine if the operating system is secure (ie Windows NT platform) – the documentation states that the IsInRole method returns no results on Windows 98 and Windows Millennium Edition. I’m not entirely sure how a method that returns a boolean value can return no results, so it is wrapped in the Secure check just in case an exception is thrown when using it on Windows 9x/ME.