C# Active Directory: Get domain name of user?

前端 未结 4 408
难免孤独
难免孤独 2020-12-02 13:43

I know that this type of question has been asked before, but other methods are failing me right now.

As it stands our windows service polls AD, given an LDAP (i.e. L

4条回答
  •  星月不相逢
    2020-12-02 14:21

    Since I could not find any example code I would like to share my own solution. This will search the parents of the DirectoryEntry object until it hits the domainDNS class.

    using System.DirectoryServices;
    
    public static class Methods
    {
        public static T ldap_get_value(PropertyValueCollection property)
        {
            object value = null;
            foreach (object tmpValue in property) value = tmpValue;
            return (T)value;
        }
    
        public static string ldap_get_domainname(DirectoryEntry entry)
        {
            if (entry == null || entry.Parent == null) return null;
            using (DirectoryEntry parent = entry.Parent)
            {
                if (ldap_get_value(parent.Properties["objectClass"]) == "domainDNS") 
                    return ldap_get_value(parent.Properties["dc"]);
                else 
                    return ldap_get_domainname(parent);
            }
        }
    }
    

    Use it like this:

    string[] _properties = new string[] { "objectClass", "distinguishedName", "samAccountName", "userPrincipalName", "displayName", "mail", "title", "company", "thumbnailPhoto", "useraccountcontrol" };
    string account = "my-user-name";
    // OR even better:
    // string account = "my-user-name@DOMAIN.local";
    
    using (DirectoryEntry ldap = new DirectoryEntry())
    {
        using (DirectorySearcher searcher = new DirectorySearcher(ldap))
        {
            searcher.PropertiesToLoad.AddRange(_properties);
            if (account.Contains('@')) searcher.Filter = "(userPrincipalName=" + account + ")";
            else searcher.Filter = "(samAccountName=" + account + ")";
            var user = searcher.FindOne().GetDirectoryEntry();
    
            Console.WriteLine("Name: " + Methods.ldap_get_value(user.Properties["displayName"]));
            Console.WriteLine("Domain: " + Methods.ldap_get_domainname(user));
            Console.WriteLine("Login: " + Methods.ldap_get_domainname(user) + "\\" + Methods.ldap_get_value(user.Properties["samAccountName"]));
        }
    }
    

    I haven't got a forest to test it on but in theory this should cut it.

提交回复
热议问题