TTT
TTT

Reputation: 28869

DirectorySearcher.FindOne() not consistent?

I have come across some code that is using the DirectorySearcher.FindOne() method with the following properties:

search.Filter = "(&(objectClass=user)(anr=" + userNameNoDomain + "))";
search.PropertiesToLoad.Add("mail");
SearchResult result = search.FindOne();

There are some users that have 2 accounts associated with their username, and each account has a different email address. The documentation states:

If more than one entry is found during the search, only the first entry is returned.

However, it seems that sometimes this call will return the first account, and other times it will return the second account. From what I can tell, the code that is in one environment seems to always return the first record, and the code in another environment seems to always return the second record. My understanding is that the code is the same in both environments, and they are both querying the same AD (presumably logged in with the same user but I need to confirm this).

My questions are, is it possible for the FindOne() method to return a different account in subsequent calls? Is there any way what I'm seeing could happen if the two environments have the same code and call the same AD logged in as the same user?

My initial assumption is that something must be different somewhere, but I want to rule out the possibility of FindOne() being able to return different accounts in this scenario before I go down a rabbit hole.

Note: I know I can just change the code to use FindAll() and then iterate through both accounts and pick the correct one, but I want to understand why I have to do this before I make that change. If the investigation leads me to discovering a difference somewhere, I may not have to change the code after all.

Upvotes: 1

Views: 111

Answers (1)

Brian Desmond
Brian Desmond

Reputation: 4503

It's not your code, it's AD picking the result to return. There's no guarantee on the order of the results you'll get back from the directory. If you hit two different DCs and get the results back in a different order, that's likely what you're seeing here.

Upvotes: 1

Related Questions