获取AD 用户信息

获取 AD 用户信息

public class UserInfo
    { 
        public string UserId { get; set; }

        public string Name { get; set; }

        public string Country { get; set; }

    }

    public static UserInfo GetUserInfo(string userId)
    {
        if (string.IsNullOrEmpty(userId))
             return null;

        string ad_path = "LDAP://192.168.101.175:389";
        string ad_username = "admin";
        string ad_password = "admin";

        DirectoryEntry root;

        try
        {
            root = new DirectoryEntry(ad_path, ad_username, ad_password, AuthenticationTypes.Secure);

            root.RefreshCache();
        }
        catch (Exception)
        {
            return new UserInfo() { Successed = false, MessageId = 0 };
        }


        DirectorySearcher search = new DirectorySearcher(root);

        search.Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + userId + "))";

        SearchResult result;

        try
        {
            result = search.FindOne();
        }
        catch (Exception)
        {
            return null;
        }

        if (result == null)
        {
             return null;
        }

        var userEntry = result.GetDirectoryEntry();

        if (userEntry == null)
        {
             return null;
        }

        // 工号:sAMAccountName  国家:  姓名:displayName

        UserInfo info = new UserInfo()
        {
            Successed = true,
            UserId = userId,

        };

        if (userEntry.Properties.Contains("displayName"))
        {
            info.Name = userEntry.Properties["displayName"][0].ToString();
        }

        return info;
    }

 

已禁用评论。