2012-08-28 38 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

相关问题