This documentation is archived and is not being maintained.

How To: Connect to an LDAP Server 

This topic provides an example of how to connect to an LDAP server.

To use the example code

  • Run the console application, using the following syntax.

ConnectLDAP.exe ldapServer user pwd domain targetOU

  1. Specify the arguments, listed in the following table, when calling the console application.

ldapServer

The server name. For example: myDC1.testDom.fabrikam.com

user

The user name. For example: user1

pwd

The password. For example: secret@~1

domain

The Active Directory domain. For example: testDom

targetOU

The target organizational unit (OU). For example: OU=samples,DC=testDom,DC=fabrikam,DC=com

Example

This example uses the LdapConnection component to connect to an LDAP server.

using System;
using System.Net;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.Security.Permissions;

namespace ConnectLDAP
{
    [DirectoryServicesPermission(SecurityAction.LinkDemand, Unrestricted = true)]

    public class LDAPConnect 
    {
        // static variables used throughout the example
        static LdapConnection ldapConnection;
        static string  ldapServer;
        static NetworkCredential credential;
        static string targetOU; // dn of an OU. eg: "OU=sample,DC=fabrikam,DC=com"

        public static void Main(string[] args)
        {
            try
            {
                GetParameters(args);  // Get the Command Line parameters

                // Create the new LDAP connection
                ldapConnection = new LdapConnection(ldapServer);        
                ldapConnection.Credential = credential;
                Console.WriteLine("LdapConnection is created successfully.");
            }
            catch (Exception e)
            {
                Console.WriteLine("\r\nUnexpected exception occured:\r\n\t" + e.GetType() + ":" + e.Message);
            }
        }

        static void GetParameters(string[] args)
        {
            // When running: ConnectLDAP.exe <ldapServer> <user> <pwd> <domain> <targetOU>

            if (args.Length != 5)
            {
                Console.WriteLine("Usage: ConnectLDAP.exe <ldapServer> <user> <pwd> <domain> <targetOU>");
                Environment.Exit(-1);// return an error code of -1
            }

            // test arguments to insure they are valid and secure

            // initialize variables
            ldapServer = args[0];
            credential = new NetworkCredential(args[1], args[2], args[3]);
            targetOU = args[4];
        }
    }
}

Compiling the Code

Security

In the example, arguments are passed in. Test arguments for validity and security before using them.

See Also

Show: