user474541
user474541

Reputation: 25

Finding a user in an OU

I have a requirement to search for a user in an OU. My solution so far is as follows :-

// s = "ou=myou1,ou=myou2,ou=muou3,dc=myad,dc=com" & t = "myad.com"

PrincipalContext context = new PrincipalContext(ContextType.Domain, t, s);
UserPrincipal user = UserPrincipal.FindByIdentity(context, "boborwhoever");
if (user != null) found him!

(please pardon the obvious pseudocode but you get the picture)

The issue I am having is that although my userPrincipal user is populated and I find 'bob' if he is in 'myou3' I can change s to "ou=myou1,dc=myad,dc=com" and still find 'bob'. So it seems that the UserPrincipal.FindByIdentity also check in sub OU's.

How do I get it to just check the OU stated? Or maybe I'm miles out and should be doing the whole thing in a better way :-)

Thanks Steve

Upvotes: 0

Views: 503

Answers (1)

Stuart
Stuart

Reputation: 1151

This is how i would do this

using System.DirectoryServices

DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://**Your connection string here**";
de.AuthenticationType = AuthenticationTypes.Secure;

DirectorySearcher search = new DirectorySearcher(de);
search.Filter = "(SAMAccountName=" + account + ")";

//What properties do we want to return?
search.PropertiesToLoad.Add("displayName");
search.PropertiesToLoad.Add("mail");

search.SearchScope = SearchScope.OneLevel //this makes it only search the specified level

SearchResult result = search.FindOne();

if (result != null)
{
     //Get Him!    }
else
{
    //Not Found
}

have used this in sharepoint workflows and it functioned fine.

Upvotes: 1

Related Questions