2010-03-18 62 views

回答

3

只要你在.NET 2.0上,這可能就像它得到的那樣好。你可以做的是增加「部門」的準則對搜索過濾器 - 這樣,你把它留給公元部門做過濾:

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之上的服務包,真的:-)

+0

這就像一個魅力,marc_s。非常感激!相信我,.NET 3.5有幾個*特性,我想利用它(其中之一)。我很欣賞改進的解決方案和DirectoryServices上的快速提示。 :) – 2010-03-19 15:39:19

0

嗯,這是我想出的。它似乎工作,但我肯定會接受建議或改進的解決方案。

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 
相關問題