Friday, September 08, 2006 12:30 PM bart

User name to SID mapping in C# using System.DirectoryServices

A problem I had today when messing around with ACLs and System.DirectoryServices: how to map a user name to a SID programmatically? I came up with the following 2-line solution:

using System;
using
System.DirectoryServices;
using
System.Security.Principal;

class
Program
{
   static void Main(string
[] args)
   {
      string path = "WinNT://BART-PC/Bart"
;
      DirectoryEntry root = new DirectoryEntry(path, null, null, AuthenticationTypes
.Secure);
      Console.WriteLine(new SecurityIdentifier((byte[])root.Properties["objectSid"
][0], 0).Value);
   }
}

In an Active Directory domain you have to alter the path to LDAP://domain/... of course; a great way to find users in AD is the DirectorySearcher class. The SecurityIdentifier class is new in .NET 2.0 and lives in the System.Security.Principal namespace.

Tip: Verification can be done with the whoami.exe tool, as shown below:

C:\Users\Bart>whoami /user

USER INFORMATION
----------------

User Name    SID
============ ==============================================
bart-pc\bart S-1-5-21-3521905859-1296307529-1522791056-1000

Enjoy the System.DirectoryServices v2.0 horsepower!

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under:

Comments

# User name to SID mapping in C# using System.DirectoryServices

Friday, September 08, 2006 9:29 PM by It's Way Too Early For This

A problem I had today when messing around with ACLs and System.DirectoryServices: how to map a user name

# Asignar nombre a un SID de otra partici?n | hilpers

Tuesday, January 20, 2009 11:26 AM by Asignar nombre a un SID de otra partici?n | hilpers

Pingback from  Asignar nombre a un SID de otra partici?n | hilpers

# omega 3 max

Tuesday, November 11, 2014 2:44 AM by omega 3 max

User name to SID mapping in C# using System.DirectoryServices - B# .NET Blog