C# – How to get DOMAIN\USER from an AD DirectoryEntry

active-directorycnet

How can I get the Windows user and domain from an Active Directory DirectoryEntry (SchemaClassName="user") object?

The user name is in the sAMAccountName property but where can I look up the domain name?

(I can't assume a fixed domain name because the users are from various subdomains.)

Best Answer

This assumes that results is a SearchResultCollection obtained from a DirectorySearcher, but you should be able to get the objectsid from a DirectoryEntry directly.

SearchResult result = results[0];
var propertyValues = result.Properties["objectsid"];
var objectsid = (byte[])propertyValues[0];

var sid = new SecurityIdentifier(objectsid, 0);

var account = sid.Translate(typeof(NTAccount));
account.ToString(); // This give the DOMAIN\User format for the account