user1711993
user1711993

Reputation: 271

Why am I getting "Object reference not set to an instance of an object" from GetDirectoryEntry()?

I have some strange error.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://11.111.111.11", "user", "1");

DirectorySearcher searcher = new DirectorySearcher(directoryEntry)
{
    PageSize = int.MaxValue,
    Filter = "(&(objectClass=user)(sAMAccountName=" + txt + "*))"
};

SearchResultCollection resultCollection = searcher.FindAll();
foreach (SearchResult result in resultCollection)
{
    if (result != null)
    {
        users.Add(new ObjectTest(
        result.GetDirectoryEntry().Properties["samaccountname"].Value as string,
        result.GetDirectoryEntry().Properties["givenName"].Value as string,
        result.GetDirectoryEntry().Properties["sn"].Value as string,
        result.GetDirectoryEntry().Properties["mail"].Value as string));
    }
}

directoryEntry.Close();

When I search some users I get collection of them and after that use them in foreach. For example: I type user and get collection with 5 users, after that I fill my array.

But some times I get collection with users that give me error here:

For example I type test and I know that I have user "test" and I see my collection with correct count, but after result.GetDirectoryEntry() I get exception Object reference not set to an instance of an object.

I can't find nothing similar on site.

Note: Collection has normal count of objects, and SearchResult is not null it has normal Path! Thank you!

Upvotes: 0

Views: 2535

Answers (1)

adv12
adv12

Reputation: 8551

Here is my comment, answer-ified:

Check the results of the Properties getters; presumably one of them is returning null, and that's where your NullReferenceException is coming from (when you try to get a null property's Value).

Edit: Couldn't delete the answer, but according to @baldpate in the comments, PropertyCollection.Item[string] will never return null, so the above is not the explanation for the NullReferenceException. In any case, the strategy for finding the source of the exception is:

  1. Put each method call on its own line and store the result in a variable.
  2. Step through your code a line at a time, testing outputs until you find the one that's null.

Upvotes: 1

Related Questions