Reputation: 149
I am working with LDAP in my Windows Forms C# project.
I created a CheckListBox, and started to create a method that queries the Active Directory for all my computers is the environment.
The method is:
public string ComputerList()
{
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://MyDomain.Local");
DirectorySearcher computerSercher = new DirectorySearcher(rootDSE);
computerSercher.PageSize = 10000;
computerSercher.Filter = "(&(objectClass=computer))";
}
I am also have as I said, a CheckListBox.
What I want to do is to have a result for the query and every computer that founds. add it to the Items property for the CheckListBox.
But I don't how even approach the result. it's not like PowerShell that gives you a list of objects...
Thank you
Upvotes: 1
Views: 2784
Reputation: 40858
You're almost there. A few things:
DirectorySearcher
doesn't get back what it considers a full page, it'll stop asking)PropertiesToLoad
collection. If you don't add anything, it'll give you every attribute with a value, which is a bunch of unnecessary data you won't use. You'll likely only want to see the cn
attribute (Common Name).FindAll()
to get the results. Make sure you wrap this in a using
statement to prevent memory leaks (the documentation says so).[0]
in most cases. For future reference (not applicable here): if a property is not set in AD, it won't be in the Properties
collection at all, so, for optional attributes, you'll have to use Properties.Contains()
to see if it's there first.Working from what you have, here is a method that will return a list of computer names:
public IEnumerable<string> ComputerList()
{
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://MyDomain.Local");
DirectorySearcher computerSercher = new DirectorySearcher(rootDSE)
{
PageSize = 1000,
Filter = "(&(objectClass=computer))"
};
computerSercher.PropertiesToLoad.Add("cn");
using (var results = computerSercher.FindAll())
{
foreach (SearchResult result in results)
{
yield return (string) result.Properties["cn"][0];
}
}
}
Update: To answer your questions in your comment:
yield
basically tells it to "add this item to the collection that will be returned". There is a little more going on in the background, which you can read about here. But in simplest terms, it saves you from having to create your own list, add items to that list and return the list.string
to IEnumerable<string>
because you are getting multiple results from your search, so I assume you want to return all of those results. This method will give you a list of computer names, not just one computer name.FindAll()
returns a SearchResultCollection
. For some reason I don't know, the objects returned from SearchResultCollection
in a foreach
are presented as object
. So you need to cast them to SearchResult
explicitly to use them.Upvotes: 1