Connecting to Active Directory via .NET

CattleDecap picture CattleDecap · Feb 11, 2015 · Viewed 7.1k times · Source

I have a virtual machine with Active Directory that I want to connect to using .NET, I've already connected to an ubuntu machine running OpenLDAP but when connecting to AD it's not working smoothly.

The code I'm attempting to connect with is as follows:

var directoryEntry = 
    new DirectoryEntry("LDAP://192.168.1.1", @"EXAMPLE\Administrator", "Abc1234");

try
{
   var test = directoryEntry.NativeObject;
}
catch (Exception e)
{
    System.Diagnostics.Debug.WriteLine(e.Message);
}

Watching the locals window the variable directoryEntry's Guid, name etc says "Function evaluation timed out".

Then when it arrives at the try block it simply says "The server is not operational".

I've also tried this code, and it fails at the "ldap.bind" telling me that "the ldap-server is unavailable".

using (var ldap = new LdapConnection("192.168.1.1:389"))
{
    ldap.AuthType = AuthType.Basic;
    ldap.SessionOptions.ProtocolVersion = 3;
    ldap.Bind(new NetworkCredential(@"EXAMPLE\Administrator", "Abc1234"));
}

I know the server is up and running, I know that they have a connection (machines can ping each other) but I can't figure out why it isn't working. Can any of you see if there are any flaws in the code? (and yes I've googled all of the errors and various questions about connecting to AD before asking this question but none of the solutions have worked).

Answer

Ravi M Patel picture Ravi M Patel · Feb 11, 2015

If you domain name is 'example.com' and let say you have an organization unit (OU) called 'users'. This works perfectly fine for me.

However the machine where this code runs, is added to the AD domain and it runs with an AD user account. If you do not have a machine added to the same domain which you are querying, you may try "Run as" option (Shift + Right Click) to launch the program or visual studio.

    public static List<string> GetAllUsers()
    {
        List<string> users = new List<string>();

        using (DirectoryEntry de = new DirectoryEntry("LDAP://OU=Users,DC=example,DC=local"))
        {
            using (DirectorySearcher ds = new DirectorySearcher(de))
            {
                ds.Filter = "objectClass=user";
                SearchResultCollection src = ds.FindAll();
                foreach (SearchResult sr in src)
                {
                    using (DirectoryEntry user = new DirectoryEntry(sr.Path))
                    {
                        users.Add(new string(user.Properties["sAMAccountName"][0].ToString()));

                    }
                }
            }

        }
        return users;
    }