How to: Create a Simple System.DirectoryServices Application

The following code example creates a fully functional System.DirectoryServices console application. This application searches Active Directory Domain Services based on an ambiguous name, which could be a user name, a user first name, a user last name, a telephone number or an office location, and displays the result.

Creating a System.DirectoryServices Console Application

  1. Open Visual Studio and click New Project.

  2. In the New Project dialog box, in the left pane, choose Visual Basic, Visual C#, or Visual J#. Then, under the language you chose, click Windows. In the Templates pane, click Console Application.

  3. Name the project and click OK.

  4. Click Project>Add Reference... and click System.DirectoryServices from the list displayed on the .NET tab.

  5. If building the C# version of the application, add a "Using System.DirectoryServices;" statement to the using statement list. If building the Visual Basic version of the application, add an "Imports System.DirectoryServices" statement to the Imports statement list.

  6. Add the following lines to the Class1 Main module.

    Imports System.DirectoryServices
    ....
    Dim src As DirectorySearcher = New DirectorySearcher("(anr=putANameHere)") 
    Dim result As SearchResult
    For Each result In src.FindAll()
        Console.WriteLine("{0} {1}", result.Properties("Name")(0), result.Properties("telephoneNumber")(0))
    Next
    
    using System.DirectoryServices;
    ... 
    DirectorySearcher src = new DirectorySearcher("(anr=putANameHere)");
    foreach(SearchResult res in src.FindAll() )
    {
        Console.WriteLine("{0} {1}", res.Properties["cn"][0], res.Properties["telephoneNumber"][0]);
    }
    
  7. Compile and run the application.

For more information and a code example of a System.DirectoryServices application that uses a Windows form, see Enumerating User Memberships.

See Also

Tasks

How to: Set Up Your Development Environment for System.DirectoryServices

Reference

System.DirectoryServices

Concepts

Enumerating User Memberships

Send comments about this topic to Microsoft.

Copyright © 2007 by Microsoft Corporation. All rights reserved.