Directory Services

Enumerating Child Objects

To enumerate objects in a container, create a DirectoryEntry object that you can use to hold each object and its properties. You can then use the properties provided by DirectoryEntry to obtain data, such as the name attribute. You can iterate through each object in the container using the foreach statement.

The following code sample shows how to enumerate a user container.

[C#]
try
{
	// Bind to the container to enumerate.
	DirectoryEntry ent = new DirectoryEntry("LDAP://CN=users,OU=Marketing,DC=fabrikam,DC=com");
	// Create an object to use for individual objects in the container and iterate
	// through the container.
	foreach( DirectoryEntry child in ent.Children)
	{
		// Write the name and path for each object in the container.
		Console.WriteLine( "{0} {1}", child.Name, child.Path);
}
}
catch
{
	// Handle errors.
}
[Visual Basic .NET]
Try
	' Bind to the container to enumerate.
	Dim ent As New DirectoryEntry("LDAP://CN=users,OU=Marketing,DC=fabrikam,DC=com")
	' Create an object to use for individual objects in the container and iterate
	' through the container.
	Dim child As DirectoryEntry
	For Each child In  ent.Children
		' Write the name and path for each object in the container.
		Console.WriteLine("{0} {1}", child.Name, child.Path)
	Next child
Catch Exception1 As Exception
	' Handle errors.
End Try