Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 328
msindle Avatar asked Sep 09 '14 18:09

msindle


1 Answers

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

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

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!

like image 137
marc_s Avatar answered Oct 26 '22 08:10

marc_s