This post demonstrates how to construct the user logonname from an ActiveDirectory DirectoryEntry instance using C#.
Well, this time nothing about SharePoint! Wow! I've decided to post this little "How To" since I've encountered this problem already many times and spent always a heck of a time looking for an answer.
Situation
I have the DirectoryEntry instance representing a user-objectClass in ActiveDirectory and I want to get his/her Windows logonname using not the full qualified name, but "<domain>\<username>" format.
Solution
Use the "distinguishedName" property and extract the first "DN=xyz" information. This is tipically the domain name you are looking for. The username portion comes then easily from the "samaccountname" property.
Example:
string
distinguishedName = ((
string)entry.Properties[
"distinguishedName"].Value);
Regex regex =
new Regex(
"(?<=DC=).+?(?=,)");
Match match = regex.Match(distinguishedName);
if (match.Success)
{
return string.Format(
"WinNT://{0}/{1}", match.Value.ToUpper(), entry.Properties[
"samaccountname"][0]);
}
else
...