Directory Services

Binding Strings

The following are code examples for how to bind to different types of objects in the directory. These statements use an LDAP syntax for its path which is used when binding to Active Directory and other LDAP directories.

Binding to the current domain (the domain that authenticates the user's connection).

[C#]
DirectoryEntry ent = new DirectoryEntry();
[Visual Basic .NET]
Dim ent As New DirectoryEntry()

Binding to a specific server.

[C#]
DirectoryEntry ent = new DirectoryEntry("LDAP://server01");
[Visual Basic .NET]
Dim ent As New DirectoryEntry("LDAP://server01")

Binding to a domain.

[C#]
DirectoryEntry ent = new DirectoryEntry("LDAP://platform.fabrikam.com");
[Visual Basic .NET]
Dim ent As New DirectoryEntry("LDAP://platform.fabrikam.com")

Binding to a specific object.

[C#]
DirectoryEntry ent = new DirectoryEntry("LDAP://CN=Joe,OU=Marketing,DC=fabrikam,DC=Com");
[Visual Basic .NET]
Dim ent As New DirectoryEntry("LDAP://CN=Joe,OU=Marketing,DC=fabrikam,DC=Com")

Binding using an alternate credential. This example uses a user name and password passed from a user interface as credentials to bind to a server.

[C#]
//GetUserNameFromUI() and GetPasswordFromUI() are functions you create to pass in information.
String userName = GetUserNameFromUI();
string password = GetPasswordFromUI();
DirectoryEntry ent = new DirectoryEntry("LDAP://server01",userName,password);
[Visual Basic .NET]
//GetUserNameFromUI() and GetPasswordFromUI() are functions you create to pass in information.
Dim userName As [String] = GetUserNameFromUI()
Dim password As String = GetPasswordFromUI()
Dim ent As New DirectoryEntry("LDAP://server01", userName, password)

Binding using flags. For a list of flags used to bind to objects in the System.DirectoryServices namespace, see AuthenticationTypes Enumeration.

[C#]
DirectoryEntry ent = new DirectoryEntry("LDAP://server01",null,null,AuthenticationTypes.ServerBind | AuthenticationTypes.FastBind);
[Visual Basic .NET]
Dim ent As New DirectoryEntry("LDAP://server01", Nothing, Nothing, AuthenticationTypes.ServerBind Or AuthenticationTypes.FastBind)

If you have used ADSI, you may know that, in C++ applications, you must release directory objects that you are bound to when you are finished with them. This is not done in System.DirectoryServices because the garbage collector cleans up the object when it leaves the scope of an operation. To clear the memory before the application leaves the scope, call the Dispose method on the bound object; that is, the DirectoryEntry.