C # get groups a user belongs to in Active Directory

I am not a programmer by nature, so I apologize in advance :) I am using code snippets from http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via -C # 39. and it was really helpful. I am using his method to get user group memberships and it also requires a method AttributeValuesMultiString

. I don't have any syntax errors, but when I call the Groups

method with Groups("username", true)

, I get the following error:

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

I dug around a bit but it doesn't seem to give an answer as to why I am getting this error.

+3


source to share


1 answer


You should check the namespace System.DirectoryServices.AccountManagement

(S.DS.AM). Read more 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 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 very easy to play with users and groups in AD!

+5


source







All Articles