C# get groups that a user is a member of in Active Directory

13,509

You should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // get the user's groups
       var groups = user.GetAuthorizationGroups();

       foreach(GroupPrincipal group in groups)
       {
           // do whatever you need to do with those groups
       }
    }

}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

Share:
13,509
msindle
Author by

msindle

Updated on June 29, 2022

Comments

  • msindle
    msindle almost 2 years

    I'm not a programmer by nature so I apologize in advance :) I'm using the code snippets from http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C#39 and it has been really helpful. I'm using his method for getting user group memberships and it requires his AttributeValuesMultiString method as well. I don't have any syntax errors but when I call the Groups method via Groups("username", true) I get the following error:

    An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in System.DirectoryServices.dll

    I have done some digging but nothing seems to really answer why I'm getting this error.

  • Joe
    Joe over 9 years
    I agree S.DS.AM is simpler - when it works. But be aware that it has bugs that Microsoft seems unable / unwilling to fix: connect.microsoft.com/VisualStudio/feedbackdetail/view/74879‌​0/…
  • Cody
    Cody over 8 years
    I always come back to having inconsistent issues with the AccountManagement DLL. It's a nightmare.
  • JsonStatham
    JsonStatham about 5 years
    @marc-s What if you want the groups that ARE NOT authorisation groups
  • Shruti
    Shruti almost 5 years
    @JsonStatham: On the user object, there is another function called user.GetGroups(). Maybe thats what you were looking for.