delete
delete

Reputation:

How to get a collection of strings of what Groups a user belongs to?

if (DomainHelpers.DomainExists(ConnectionString))
{
    using(var baseDirectory = new DirectoryEntry(ConnectionString))
    {
        baseDirectory.Username = Username;
        baseDirectory.Password = Password;

        using (DirectorySearcher searcher = new DirectorySearcher())
        {
            searcher.SearchRoot = baseDirectory;
            searcher.Filter = "(objectCategory=user)";
            searcher.SearchScope = SearchScope.Subtree;

            var userResults = searcher.FindAll();

            foreach (SearchResult user in userResults)
            {
                var newUser = new User();
                newUser.Name = user.Properties["name"][0].ToString();
                newUser.Path = user.Path;

                //.Groups is just a List<string>.
                newUser.Groups = user.Properties?????

                _users.Add(newUser);
            }
        }
    }
}

How do I retrieve a collection of groups the user belongs to?

Thank you! :)

Upvotes: 0

Views: 340

Answers (2)

Harvey Kwok
Harvey Kwok

Reputation: 11873

You should use System.DirectoryServices.AccountManagement. It's much easier. Here is a nice code project article giving you an overview on all the classes in this DLL.

It's really hard to get it right using DirectoryEntry. First of all, getting memberOf attribute doesn't give you primary group. Also, if the user has a domain local group from another domain, it won't show up in memberOf attribute. You can check here for details. Here is how the code looks like if you switch to use System.DirectoryServices.AccountManagement. The following code can find the immediate groups this user assigned to, which includes the primary group.

UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext (ContextType.Domain, "mydomain.com"), IdentityType.SamAccountName, "username");
foreach (GroupPrincipal group in user.GetGroups())
{
    Console.Out.WriteLine(group);
}

Upvotes: 0

manji
manji

Reputation: 47978

user.Properties["memberOf"]

don't forget to add searcher.PropertiesToLoad.Add("memberOf"); before ...searcher.FindAll()

To populate your property:

//.Groups is just a List<string>.
foreach(object group in user.Properties["memberOf"])
    newUser.Groups.Add((string)group);

Upvotes: 1

Related Questions