This is a quick sample code that I used quite often on customer sites:
- To Check whether or not I am a local admin on my machine.
- To quickly list what Windows groups my user account is part of.
To compile this code, you only need to:
- If you are using Visual Studio 2005 (or above):
- Create a “C# Console Appliation” project.
- Copy and paste the code below in “Program.cs”
- Check the target Runtime (.NET Framework 2.0 or above – it might work in earlier version, but I did not try).
- You only need to reference “System.dll”.
- Compile and run.
- If you are using the .NET SDK:
- Copy and paste the code into a “.cs” file
- Compile the code using the C# compiler (csc.exe). You only need to reference “System.dll”.
- Run it.
Here is the code sample (Program.cs – Renamed the file to “.cs”) :
using System.Security.Principal;
namespace AmIAdmin
{
class Program
{
static void Main(string[] args)
{
WindowsIdentity wi = WindowsIdentity.GetCurrent();
Display(@"Name", wi.Name);
Display(@"Owner.AccountDomainSid", wi.Owner.AccountDomainSid.ToString());
Display(@"User.AccountDomainSid", wi.User.AccountDomainSid.ToString());
Display(@"IsAnonymous?", wi.IsAnonymous.ToString());
Display(@"IsAuthenticated?", wi.IsAuthenticated.ToString());
Display(@"IsGuest?", wi.IsGuest.ToString());
Display(@"IsSystem?", wi.IsSystem.ToString());
Display(@"");
Display(@"IsIn 'BUILTIN\Users'?", IsInWindowsGroup(@"BUILTIN\Users", wi.Groups).ToString());
Display(@"IsIn 'BUILTIN\Administrators'?", IsInWindowsGroup(@"BUILTIN\Administrators", wi.Groups).ToString());
Display(@"");
Display(@"Groups:");
foreach (IdentityReference ir in wi.Groups)
{
NTAccount ntAcc = ir.Translate(typeof(NTAccount)) as NTAccount;
string s = string.Format(@"'{0}' [{1}]", ntAcc.Value, ir.Value);
Display(@"Group", s);
}
System.Console.Out.WriteLine();
System.Console.Out.WriteLine(@"... Press Return ...");
System.Console.In.ReadLine();
}
//static bool IsInWindowsGroup(WindowsBuiltInRole role, IdentityReferenceCollection groups)
static bool IsInWindowsGroup(string role, IdentityReferenceCollection groups)
{
bool isInGroup = false;
foreach (IdentityReference ir in groups)
{
NTAccount ntAcc = ir.Translate(typeof(NTAccount)) as NTAccount;
if (role.CompareTo(ntAcc.Value) == 0)
{
isInGroup = true;
break;
}
}
return(isInGroup);
}
static void Display(string libelle, string msg)
{
string s = string.Format(@"{0}: {1}", libelle, msg);
System.Console.Out.WriteLine(s);
}
static void Display(string msg)
{
System.Console.Out.WriteLine(msg);
}
}
}
P.S.
Here is the link (http://en.support.wordpress.com/code/posting-source-code/) I used to correctly post sample code.

Mister W
/ March 16, 2011Nice website…
However I can’t find the WPF section 😉