Search code examples
asp.netldapcustom-membershipprovider

ASP.NET Bind and Query LDAP


So I have been driving myself crazy trying to figure out why I can't get my LDAP search to work.

private String getDNFromLDAP(String strUID)
    {
        String strDN = "";

        //Create an LDAP Entry Object
        DirectoryEntry entry = new DirectoryEntry("LDAP://something.blah.com/cn=people,dc=blah,dc=com");
        entry.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;
        entry.Username = "cn=myaccount,cn=special,dc=blah,dc=com";
        entry.Password = "supersecret";

        DirectorySearcher mySearcher = new DirectorySearcher(entry);
        mySearcher.SearchScope = SearchScope.Subtree;
        mySearcher.Filter = "(uid=" + strUID + ")";
        SearchResult result = mySearcher.FindOne();

        int nIndex = result.Path.LastIndexOf("/");
        strDN = result.Path.Substring((nIndex + 1)).ToString().TrimEnd();

        //Clean up objects
        entry.Close();
        entry.Dispose();
        mySearcher.Dispose();

        //returns the DN
        return strDN;
    }

I know the object I am searching for exist (confirmed with ldapsearch), but my result keeps coming back empty. I suspect there is an issue with the base dn, but I don't know how to confirm what what DirectorySearch is using as the base dn. Any help at all would be appreciated.


Solution

  • You set the root using the searchroot property. The root is set to entry you pass on the constructor, so this might be why you can't find your entry.