编程活动目录

时间:2009-05-23 16:53:08

标签: active-directory

我运行了一个asp应用程序,但我想搜索Active Directory。

我正在使用vb(visual web developer 2008)

如何搜索给定用户的活动目录?

即:用户在文本框中输入登录名,点击提交。对该用户单击搜索活动目录。当找到用户信息时显示。

由于

1 个答案:

答案 0 :(得分:3)

您可以使用哪种版本的.NET框架?在.NET 3.5中搜索和查找AD中的内容变得非常容易 - 请参阅Ethan Wilanski和Joe Kaplan关于使用安全主体API的great MSDN article

如果您还没有使用.NET 3.5,则必须使用DirectorySearcher类并根据需要设置搜索过滤器。正确使用LDAP过滤器可能是最大的障碍。

Robbie Allen还有两篇关于System.DirectoryServices编程的精彩介绍: - Part 1 - Part 2

http://www.directoryprogramming.net(Joe Kaplan的网站 - 他是Microsoft Active Directory MVP)有一些非常好的资源,Richard Mueller有一些很好的参考excel表,介绍了每个ADSI提供商可用的属性,以及他们的意思以及他们的LDAP名称是什么 - 请参阅http://www.rlmueller.net

马克

编辑:好的 - 这是.NET 2.0 / 3.0方法:

// set the search root - the AD container to search from
DirectoryEntry searchRoot = new DirectoryEntry("LDAP://dc=yourdomain,dc=com");

// create directory searcher
DirectorySearcher ds = new DirectorySearcher(searchRoot);

ds.SearchScope = SearchScope.Subtree;

// set the properties to load in the search results
// the fewer you load, the better your performance    
ds.PropertiesToLoad.Add("cn");
ds.PropertiesToLoad.Add("sn");
ds.PropertiesToLoad.Add("givenName");
ds.PropertiesToLoad.Add("mail");

// set the filter - here I'm using objectCategory since this attribute is
// single-valued and indexed --> much better than objectClass in performance
// the "anr" is the "ambiguous name resolution" property which basically
// searches for all normally interesting name properties
ds.Filter = "(&(objectCategory=person)(anr=user-name-here))";

// get the result collection
SearchResultCollection src = ds.FindAll();

// iterate over the results
foreach (SearchResult sr in src)
{
    // do whatever you need to do with the search result
    // I'm extracting the properties I specified in the PropertiesToLoad
    // mind you - a property might not be set in AD and thus would
    // be NULL here (e.g. not included in the Properties collection)
    // also, all result properties are really multi-valued, so you need
    // to do this trickery to get the first of the values returned
    string surname = string.Empty;
    if (sr.Properties.Contains("sn"))
    {
        surname = sr.Properties["sn"][0].ToString();
    }

    string givenName = string.Empty;
    if (sr.Properties.Contains("givenName"))
    {
        givenName = sr.Properties["givenName"][0].ToString();
    }

    string email = string.Empty;
    if (sr.Properties.Contains("mail"))
    {
        email = sr.Properties["mail"][0].ToString();
    }

    Console.WriteLine("Name: {0} {1} / Mail: {2}", givenName, surname, email);
 }

希望这有帮助!

马克