使用用户输入在Active Directory中搜索计算机名称

时间:2012-08-28 05:12:53

标签: c# active-directory

您好我试图在我的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
}

1 个答案:

答案 0 :(得分: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....     
   }
}    

如果您不需要找到一台计算机,但搜索整个计算机列表,则可以使用新的PrincipalSearcher界面,这基本上允许您设置“QBE”(查询 - 通过示例)您正在寻找的对象,定义搜索条件,然后搜索这些条件的匹配项。

新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!