查询LDAP

时间:2011-06-23 10:24:41

标签: c# ldap

我之前没有使用过LDAP,所以我有点迷失了。我需要连接到LDAP源查找特定属性并进行更改。该程序的输入是一个包含用户列表的CSV文件。该程序应该从CSV文件中读取UID,找到LDAP中的记录并替换某个属性。我不知道如何做到这一点。任何人都可以指出我正确的方向吗?

3 个答案:

答案 0 :(得分:23)

@KenL几乎让我在那里。我还必须设置DirectoryEntry的AuthenticationType才能使其正常工作。另外,请注意您使用通配符的方式(Kleene Stars)。

DirectoryEntry rootEntry = new DirectoryEntry("LDAP://some.ldap.server.com");
rootEntry.AuthenticationType = AuthenticationTypes.None; //Or whatever it need be
DirectorySearcher searcher = new DirectorySearcher(rootEntry);
var queryFormat = "(&(objectClass=user)(objectCategory=person)(|(SAMAccountName=*{0}*)(cn=*{0}*)(gn=*{0}*)(sn=*{0}*)(email=*{0}*)))";
searcher.Filter = string.Format(queryFormat, searchString);
foreach(SearchResult result in searcher.FindAll()) 
{
    Console.WriteLine("account name: {0}", result.Properties["samaccountname"].Count > 0 ? result.Properties["samaccountname"][0] : string.Empty);
    Console.WriteLine("common name: {0}", result.Properties["cn"].Count > 0 ? result.Properties["cn"][0] : string.Empty);
}

答案 1 :(得分:20)

第一个响应元素,使用ADSI(旧时尚)

How to do Almost everything (with ADSI) on Active Directory with C#

第二个响应元素,开始使用.NET 3.5 Microsoft引入了“ Principal ”和“ AccountManagement ”。

How to do Almost everything (with AccountManagement) on Active Directory with C#

第三响应元素,您可以使用System.DirectoryServices.Protocols (S.DS.P)的低级别(本机LDAP)协议。

  

备注:如果您对如何从本机代码询问活动目录感兴趣,可以查看RFC C23中指定的LDAP C-Binding API,Microsoft支持它,请参阅{ {3}}。您可以找到MS Strategy for Lightweight Directory Access Protocol (LDAP)的使用和参考手册。

答案 2 :(得分:14)

代码明智,它比你想象的要简单得多。您需要创建与目录的连接,设置搜索器,然后按属性名称搜索。

DirectoryEntry entry = new DirectoryEntry("LDAP://MyDomain.com");
DirectorySearcher dSearch = new DirectorySearcher(entry);
dSearch.Filter = "(&(objectCategory=person)(objectClass=user)(" + SType + "=" + Name + "))";

SType是名称类型,Name是实际用户名