如何异步查询Active目录。 我有一些代码可以同步获取用户
Dim UserName as string = ""
Dim Password as string = ""
Dim LDAPPath As String = ""
Dim DirectoryE As DirectoryEntry = New DirectoryEntry(LDAPPath, UserName, Password)
Dim RootDSE As DirectoryServices.DirectoryEntry = globalroot
Dim objSearch As New System.DirectoryServices.DirectorySearcher(RootDSE)
Dim oResult As DirectoryServices.SearchResultCollection = Nothing
'objSearch.PropertiesToLoad.Add("uid")
'objSearch.PropertiesToLoad.Add("cn")
objSearch.Filter = "(&(objectcategory=user))"
objSearch.PageSize = 500
oResult = objSearch.FindAll
For Each ldentry As SearchResult In oResult
Console.WriteLine(ldentry.Properties("cn")(0).ToString)
Next
Console.ReadLine()
答案 0 :(得分:0)
假设您使用的是.NET 4.5。将代码更改为返回SearchResultCollection
:
Private Function GetAllUsers() As SearchResultCollection
Dim UserName As String = ""
Dim Password As String = ""
Dim LDAPPath As String = ""
Dim DirectoryE As DirectoryEntry = New DirectoryEntry(LDAPPath, UserName, Password)
Dim RootDSE As DirectoryServices.DirectoryEntry = New DirectoryEntry("LDAP://RootDSE")
Dim objSearch As New System.DirectoryServices.DirectorySearcher(RootDSE)
Dim oResult As DirectoryServices.SearchResultCollection = Nothing
'objSearch.PropertiesToLoad.Add("uid")
'objSearch.PropertiesToLoad.Add("cn")
objSearch.Filter = "(&(objectcategory=user))"
objSearch.PageSize = 500
Return objSearch.FindAll
End Function
然后这样称呼:
Private Async Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
For Each ldentry As SearchResult In Await Task.Run(Function() GetAllUsers())
Console.WriteLine(ldentry.Properties("cn")(0).ToString)
Next
Console.ReadLine()
End Sub