我之前没有使用过LDAP,所以有点迷失。我需要连接到LDAP源,找到特定的属性并将其更改。程序的输入是一个包含用户列表的CSV文件。该程序应该从CSV文件中读取UID,找到LDAP记录并替换某个属性。我不知道如何做这件事。请问有人能指点我该怎么做吗?
我之前没有使用过LDAP,所以有点迷失。我需要连接到LDAP源,找到特定的属性并将其更改。程序的输入是一个包含用户列表的CSV文件。该程序应该从CSV文件中读取UID,找到LDAP记录并替换某个属性。我不知道如何做这件事。请问有人能指点我该怎么做吗?
@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);
}
响应的第一个元素,使用 ADSI(老式)。
如何使用 C# 在 Active Directory 上通过 ADSI 实现几乎所有功能
响应的第二个元素,从 .NET 3.5 开始,Microsoft 引入了“Principal”和“AccountManagement”。
如何使用 C# 和 AccountManagement 在 Active Directory 上实现几乎所有功能
响应的第三个元素,您可以使用低级别(本机 LDAP)协议并结合System.DirectoryServices.Protocols (S.DS.P)。
备注:如果您想了解如何从本机代码查询活动目录,可以查看 RFC 1823 中描述的 LDAP C 绑定 API。Microsoft 对其进行支持,请参见轻型目录访问协议 (LDAP) 的 MS 策略。您可以在Microsoft API in Lightweight Directory Access Protocol 的使用和参考手册中找到相关信息。
从代码角度来看,它比您想象的要简单得多。您需要创建一个连接到目录的对象,设置搜索器,然后按属性名称进行搜索。
DirectoryEntry entry = new DirectoryEntry("LDAP://MyDomain.com");
DirectorySearcher dSearch = new DirectorySearcher(entry);
dSearch.Filter = "(&(objectCategory=person)(objectClass=user)(" + SType + "=" + Name + "))";
SType是类型名称,Name是实际用户名。