views:

85

answers:

1

How can I about getting a user's group memberships from AD, preferably using the same pattern as I use to get the user's Department property, as below? I have found several examples, but the intersecting set of all example techniques is quite small, and lacks the tightness and simplicity of this Department query:

        var adServer = ConfigurationManager.AppSettings["adServer"] ?? "localhost";
        var remoteRoot = new DirectoryEntry(GetRootPath(adServer));
        var searcher = new DirectorySearcher(remoteRoot, string.Format("(SAMAccountName={0})", shortUserName));

        searcher.PropertiesToLoad.Add("Department");
        SearchResult result = null;
        result = searcher.FindOne();
+1  A: 

Are you on .NET 3.5 ? If so, it's very easy:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");

string userName = "yourUser";

UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName);

PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups();

Find your user, and then call the .GetAuthorizationGroups() on your user principal - that returns all groups the user belongs to, including his primary group, and any nested group memberships.

Check out this MSDN article for more new goodness in .NET 3.5 when it comes to dealing with AD.

In .NET 2.0, things are a lot messier...

marc_s
Thanks. That's half working, but I get an error "Can't access domain info" (something like that) when I call GetAuthorizationGroups()
ProfK
did you specify your NetBIOS domain Name when constructing the principal context? E.g. "YOURDOMAIN", instead of "yourcompany.com" ?
marc_s
works for me. Saved me a lot of work! Thanks
paul