Question

I have AD domain name like MyDomain.com and Windows logon domain name like MD (MD=MyDomain). How I can get win logon domain name from AD domain using DirectoryEntry.Properties collection?

Was it helpful?

Solution

Probably, you could use this:

string username = "<username>";

DirectoryEntry de = new DirectoryEntry(
    "LDAP://" + ConfigurationManager.AppSettings["ADDomain"],
    ConfigurationManager.AppSettings["ADUsername"],
    ConfigurationManager.AppSettings["ADPassword"]);

DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = string.Format("samaccountname={0}",
    (username.Split('\\').Length > 1) ? username.Split('\\')[1] : username);

SearchResult result = ds.FindOne();
if (result == null)
    throw new ArgumentException(
        string.Format("Username '{0}' does not exist in the active directory", username), "username");

You can then use the Properties collection on the SearchResult object to get information from the user object (e.g. result.Properties["samaccountname"]). Some useful keys are:

  • List item samaccountname (Windows username)
  • List item displayName (Full name)
  • List item telephoneNumber
  • List item mail (email address)
  • List item department (the department the user belongs to)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top