Active Directory读取用户属性

时间:2014-07-31 14:18:15

标签: c# winforms visual-studio-2010 active-directory ldap

我试图让我的winform系统使用活动目录中人员的用户名进行身份验证。我现在使用以下代码。但结果是空的!!

 private static string LDAP_Connection = "corp.mycompany.global";
 private static string LDAP_Path = "LDAP://OU=USERS,OU=BT,OU=EC,OU=tres,DC=corp,DC=company,DC=global";



 static DirectoryEntry createDirectoryEntry()
        {
            // create and return new LDAP connection with desired settings  

            DirectoryEntry ldapConnection = new DirectoryEntry(LDAP_Connection);
            ldapConnection.Path = LDAP_Path;
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;

            return ldapConnection;
        } 



public static void RetreiveUserInfoAdvanced()
{
    try
    {
        // create LDAP connection object  

        DirectoryEntry myLdapConnection = createDirectoryEntry();

        // create search object which operates on LDAP connection object  
        // and set search object to only find the user specified  

        DirectorySearcher search = new DirectorySearcher(myLdapConnection);
        //search.Filter = "(mail  =" + _userlogin + ")";
        search.Filter = "mail  = a.ghew@mycompany.com";

        // create results objects from search object  

        //SearchResult result = search.FindOne();

        string[] requiredProperties = new string[] { "cn", "mail" };  

            foreach (String property in requiredProperties)   
               search.PropertiesToLoad.Add(property);  

            SearchResult result = search.FindOne();  

            if (result != null)  
            {  
               foreach (String property in requiredProperties)  
                  foreach (Object myCollection in result.Properties[property])   
                     Console.WriteLine(String.Format("{0,-20} : {1}", property, myCollection.ToString())); 

            }
    }
}

我使用相同数据的Ad Explorer,一切都找到了正常工作,我可以达到所需的数据。但是从我的系统来看,

1 个答案:

答案 0 :(得分:1)

我没有您的AD环境,但我在类似配置中执行了以下操作:

DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(mail=a.ghew@mycompany.com)";
search.SearchScope = SearchScope.Subtree;

放手一搏?基本上删除过滤器表达式中的空格并确保已启用遍历。