Reputation: 93
I have the following code, which retrieves all the active directory groups a specific user belongs to:-
string[] output = null;
using (var ctx = new PrincipalContext(ContextType.Domain, "???.???.uk"))
using (var user = UserPrincipal.FindByIdentity(ctx, username))
{
if (user != null)
{
output = user.GetGroups() //this returns a collection of principal objects .Select(x => x.SamAccountName) // select the name. you may change this to choose the display name or whatever you want
.ToArray(); // convert to string array
}
}
The only problem I have is when the domain controller is down. I thought the above code would simply look through other controllers until it found one that was up. How can I rewrite the above code, so that it doesn't fall over when a single domain controller is unavailable?
Thanks
Upvotes: 0
Views: 249
Reputation: 11364
If you want to use any available domain controller, if there is one, you can use the name of the domain instead of defining the controller.
using (var ctx = new PrincipalContext(ContextType.Domain, "example.uk"))
Another thing you can do is get a list of all the domain controllers and filter them to get the first available controller
Domain domain = Domain.GetCurrentDomain();
var allControllers = domain.DomainControllers;
Once you find a working controller, you can use that to create your context
Upvotes: 1