How can I get DOMAIN\USER from an AD DirectoryEntry?
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
To get the DirectoryEntry domain name you can use recursion on
directoryEntry.Parent
.
And then if directoryEntry.SchemaClassName == "domainDNS"
you can get the domain name like this:
directoryEntry.Properties["Name"].Value
You won't find what you're looking for in the DirectoryEntry, unfortunately.
You have the sAMAccountName
which typically is something like myuser
(without the domain). You have the distinguishedName
which is something like LDAP://cn=joe myuser,cn=Users,dc=yourCompany,dc=com
. You also have a userPrincipalName
but that's usually a name in the format of [email protected]
.
But you won't find any attribute that has the domain\MyUser
in it, unfortunately. You'll have to put that together from your information about the domain name, and the sAMAccountName of the DirectoryEntry.
For more information and some excellent Excel sheets on all the LDAP and WinNT properties in System.DirectoryServices, check out the Hilltop Lab website by ADSI MVP Richard Mueller.
Marc