Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // NOTE: implement IDisposable and dispose of this if not null when done.
- private DirectoryEntry userSearchRoot = null;
- private UserPrincipal FindUserInGlobalContext( string userName )
- {
- using (PrincipalSearcher userSearcher = new PrincipalSearcher())
- {
- using (PrincipalContext context
- = new PrincipalContext( ContextType.Domain ))
- {
- userSearcher.QueryFilter = new UserPrincipal( context );
- DirectorySearcher searcher
- = (DirectorySearcher)userSearcher.GetUnderlyingSearcher();
- // I usually set the GC path from the existing search root
- // by doing some string manipulation based on our domain
- // Your code would be different.
- string GCPath = ...set GC path..
- // lazy loading of the search root entry.
- if (userSearchRoot == null)
- {
- userSearchRoot = new DirectoryEntry( GCPath );
- }
- searcher.SearchRoot = userSearchRoot;
- using (PrincipalContext gcContext =
- new PrincipalContext( ContextType.Domain,
- null,
- GCPath.Replace("GC://",""))
- {
- UserPrincipal userFilter = new UserPrincipal( gcContext );
- userFilter.SamAccountName = userName;
- userSearcher.QueryFilter = userFilter;
- return userSearcher.FindOne() as UserPrincipal;
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment