Search code examples
c#active-directoryactive-directory-group

Accessing active directory from C#


I am trying to access directory in XXX domain from my console application.

             DirectoryEntry oDE = new DirectoryEntry("LDAP://DC=XXXX,DC=myDomain,DC=com");

            using (DirectorySearcher ds = new DirectorySearcher(oDE))
            {
                ds.PropertiesToLoad.Add("name");
                ds.PropertiesToLoad.Add("userPrincipalName");

                ds.Filter = "(&(objectClass=user))";

                SearchResultCollection results = ds.FindAll();

                foreach (SearchResult result in results)
                {
                    Console.WriteLine("{0} - {1}",
                        result.Properties["name"][0].ToString(),
                        result.Properties["userPrincipalName"][0].ToString());
                }
            }

when the line SearchResultCollection results = ds.FindAll(); executes I receive the error "There is no such object on the server."

what i am doing wrong?


Solution

  • Ok, so short resume of our 'chat' in the comments:

    Your current problem is caused because you don't format the LDAP uri correctly.

    LDAP URI Buildup = "LDAP://DC="

    followed by your server uri (e.g. Test1.Test2.gov.lk) where you replace the '.' with ',DC='

    So, Test1.Test2.gov.lk becomes 'LDAP://DC=Test1,DC=Test2,DC=gov,DC=lk'

    I can't help you with your followup problem; I suggest creating a new question for that.

    Good Luck,

    Nick.