Search code examples
c#winformsactive-directorydirectoryentry

How i can get windows logon domain name from AD domain name


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?


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)