【发布时间】:2010-03-18 18:34:06
【问题描述】:
这是我想要做的:
我想使用 VB.Net 和 DirectoryServices 从 Active Directory 中获取属于特定部门(由用户输入)的所有用户和组的列表。
有什么建议吗?
【问题讨论】:
标签: vb.net .net-2.0 active-directory directoryservices
这是我想要做的:
我想使用 VB.Net 和 DirectoryServices 从 Active Directory 中获取属于特定部门(由用户输入)的所有用户和组的列表。
有什么建议吗?
【问题讨论】:
标签: vb.net .net-2.0 active-directory directoryservices
只要您使用的是 .NET 2.0,那可能就已经是最好的了。您可以做的是将“部门”标准添加到您的搜索过滤器中 - 这样,您就可以将其留给 AD 来按部门进行过滤:
Private Sub GetUsersByDepartment(ByVal department as String)
Dim deGlobal As DirectoryEntry = New DirectoryEntry(ADPath, ADUser, ADPassword)
Dim ds As DirectorySearcher = New DirectorySearcher(deGlobal)
ds.Filter = "(&(objectCategory=person)(objectClass=user)(department=" & department & "))"
ds.SearchScope = SearchScope.Subtree
For Each sr As SearchResult In ds.FindAll
Dim newDE As DirectoryEntry = New DirectoryEntry(sr.Path)
If Not newDE Is Nothing Then
*Do Something*
End If
Next
End Sub
这肯定会有所帮助 - 我希望作为一名 C# 程序员,我没有搞砸你的 VB 代码!
LDAP 过滤器基本上允许您在“anded”括号内包含任意数量的条件(两个条件周围的 (&....) - 您可以像我一样轻松地将其扩展到三个条件)。
如果您有机会升级到 .NET 3.5,则有一个名为 System.DirectoryServices.AccountManagement 的新命名空间可用,它为处理用户、组、计算机和搜索提供了更好、更“直观”的方法。
查看 MSDN 文章 Managing Directory Security Principals in the .NET Framework 3.5 了解更多信息。
你可以做的是例如“按示例搜索”,因此您可以创建一个 UserPrincipal 并设置您要过滤的那些属性,然后将该对象作为“模板”进行搜索:
UserPrincipal user = new UserPrincipal(adPrincipalContext);
user.Department = "Sales";
PrincipalSearcher pS = new PrincipalSearcher(user);
PrincipalSearchResult<Principal> results = pS.FindAll();
// now you could iterate over the search results and do whatever you need to do
确实很整洁!但不幸的是,仅在 .NET 3.5 上......但等等 - 这只是 .NET 2 之上的一个服务包,真的:-)
【讨论】:
嗯,这就是我想出的。它似乎有效,但我当然愿意接受建议或改进的解决方案。
Private Sub GetUsersByDepartment(ByVal department as String)
Dim deGlobal As DirectoryEntry = New DirectoryEntry(ADPath, ADUser, ADPassword)
Dim ds As DirectorySearcher = New DirectorySearcher(deGlobal)
ds.Filter = "(&(objectCategory=person)(objectClass=user))"
ds.SearchScope = SearchScope.Subtree
For Each sr As SearchResult In ds.FindAll
Dim newDE As DirectoryEntry = New DirectoryEntry(sr.Path)
If Not newDE Is Nothing Then
If newDE.Properties.Contains("department") Then
If newDE.Properties("department")(0).ToString = department Then
*Do Something*
End If
End If
End If
Next
End Sub
【讨论】: