65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 .NET 访问 Active Directory

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.67/5 (18投票s)

2007年6月7日

CPOL
viewsIcon

51745

访问 Active Directory

引言

访问 Active Directory (AD) 是一个内联网应用程序最基本的场景之一。但对于新的开发者来说,有时这会变得很麻烦。但请相信我,这就像击打一个正球(这显示了我有多喜欢板球)。

Using the Code

以下代码展示了如何使用 C# 实现。请记住包含 System.DirectoryServices。 如下所示:

public static Hashtable SearchLDAP(string userID)
{
    DirectoryEntry entry = new DirectoryEntry("LDAP://DC=Domain,DC=com");
    DirectorySearcher mySearcher = new DirectorySearcher(entry);
    mySearcher.Filter = "(&(objectClass=user)(anr="+ userID +"))";

    mySearcher.PropertiesToLoad.Add("givenname");
    mySearcher.PropertiesToLoad.Add("sn");
    mySearcher.PropertiesToLoad.Add("mail");
    mySearcher.PropertiesToLoad.Add("description");
    mySearcher.PropertiesToLoad.Add("l");

    Hashtable associateDetailsTable = new Hashtable();
    ResultPropertyValueCollection resultCollection;
    SearchResult searchResult = mySearcher.FindOne();

    associateDetailsTable.Add("AssociateID", userID);
    if(searchResult != null)
    {
    resultCollection = searchResult.Properties["givenname"];
    foreach(object result in resultCollection)
    {
    associateDetailsTable.Add("FirstName", result.ToString());
    }
    resultCollection = searchResult.Properties["sn"];
    foreach(object result in resultCollection)
    {
    associateDetailsTable.Add("LastName", result.ToString());
    }
    resultCollection = searchResult.Properties["mail"];
    foreach(object result in resultCollection)
    {
    associateDetailsTable.Add("Mail", result.ToString());
    }
    resultCollection = searchResult.Properties["description"];
    foreach(object result in resultCollection)
    {
    associateDetailsTable.Add("Designation", result.ToString());
    }
    resultCollection = searchResult.Properties["l"];
    foreach(object result in resultCollection)
    {
    associateDetailsTable.Add("Location", result.ToString());
    }
    }
    return associateDetailsTable;
}

历史

  • 2007 年 6 月 7 日:初始发布
© . All rights reserved.