2 out of 18 rated this helpful - Rate this topic

DirectorySearcher Example 

The following code examples show how to search for all users in a domain. It contains some basic required tasks such as using a C# try-catch or Visual Basic .NET try-catch-finally statement to catch errors and error handling for all the errors that can be thrown by the DirectorySearcher object.

try
{
    // Bind to the users container.
    DirectoryEntry entry = new DirectoryEntry("LDAP://CN=users,DC=fabrikam,DC=com");
    // Create a DirectorySearcher object.
    DirectorySearcher mySearcher = new DirectorySearcher(entry);
    // Create a SearchResultCollection object to hold a collection of SearchResults
    // returned by the FindAll method.
    SearchResultCollection result = mySearcher.FindAll();
    // Get search results. For more information, see Getting Search Results.
    // ...
    // This sample uses Try...Catch to catch errors.
    // Create an Exception object. For more information, see System.Exception.
}
catch (System.Runtime.InteropServices.COMException)
{
    System.Runtime.InteropServices.COMException exception = new System.Runtime.InteropServices.COMException();
    Console.WriteLine(exception);
}
catch (InvalidOperationException)
{
    InvalidOperationException InvOpEx = new InvalidOperationException(); 
    Console.WriteLine(InvOpEx.Message);
}
catch (NotSupportedException)
{
    NotSupportedException NotSuppEx = new NotSupportedException();
    Console.WriteLine(NotSuppEx.Message);
}

See Also

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Getting Search Result
For accessing search results, see the MSDN topic, "Getting Search Results".  http://msdn.microsoft.com/en-us/library/ms180881(VS.80).aspx
Getting Search Results
http://msdn.microsoft.com/en-US/library/ms180881(v=VS.80).aspx $0$0 $0
Error in C# code?
Seems like there's an error in the C# example. In the catch code a new instance of the exception type is made. Overriding the initial exception.
See getting results
There is comment in code as below, but it doesn't link to anything - can you provide please:
// Get search results. For more information, see Getting Search Results.