2012-08-28 46 views
5

你好,我被困在試圖添加一個函數到我的Windows窗體程序中,允許用戶在文本框中鍵入他們想要搜索的計算機或計算機活動目錄。用戶將在文本框中輸入搜索字符串,然後點擊按鈕,匹配該搜索結果的計算機將出現在單獨的搜索框中。這是我的代碼到目前爲止。使用用戶輸入搜索Active Directory中的計算機名稱

我也希望每個計算機名是在單獨一行如:

computername1    
computername2   
computername3 

謝謝!

這是裏面的按鈕看起來像:

List<string> hosts = new List<string>(); 
DirectoryEntry de = new DirectoryEntry(); 
de.Path = "LDAP://servername"; 

try 
{ 
    string adser = txtAd.Text; //textbox user inputs computer to search for 

    DirectorySearcher ser = new DirectorySearcher(de); 
    ser.Filter = "(&(ObjectCategory=computer)(cn=" + adser + "))"; 
    ser.PropertiesToLoad.Add("name"); 

    SearchResultCollection results = ser.FindAll(); 

    foreach (SearchResult res in results) 
    //"CN=SGSVG007DC" 
    { 
     string computername = res.GetDirectoryEntry().Properties["Name"].Value.ToString(); 
     hosts.Add(computername); 
     //string[] temp = res.Path.Split(','); //temp[0] would contain the computer name ex: cn=computerName,.. 
     //string adcomp = (temp[0].Substring(10)); 
     //txtcomputers.Text = adcomp.ToString(); 
    } 

    txtcomputers.Text = hosts.ToString(); 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.ToString()); 
} 
finally 
{ 
    de.Dispose();//Clean up resources 
} 
+0

你應該[接受你以前的一些問題的答案](http://meta.stackexchange.com/q/5234/153998)。這表示你對那些花時間幫助你的人表示感謝,並且這會提高他們回答你可能遇到的任何問題的可能性。 –

回答

7

如果你在.NET 3.5及以上,你應該看看System.DirectoryServices.AccountManagement(S.DS.AM)命名空間。在這裏閱讀全部內容:

基本上,你可以定義域範圍內,並可以輕鬆地查找用戶和/或組AD:

// set up domain context 
using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) 
{ 
    // find a computer 
    ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, "SomeComputerName"); 

    if(computer != null) 
    { 
     // do something here....  
    } 
}  

如果你不需要找到一臺電腦,而是搜索整個電腦列表,你可以使用新的界面,其中基本上是al使您無法設置您要查找的「QBE」(按實例查詢)對象,定義搜索條件,然後搜索匹配條件。

新的S.DS.AM可以很容易地與AD中的用戶和羣組玩耍!

+0

謝謝,生病了看。 – Boundinashes6

相關問題