Search code examples
c#active-directoryactive-directory-group

how to check whether a user is a member of distribution list/security group in AD C#


I am using below piece of code to check the whether a given user is part of distribution group in AD.

static bool IsUserMemberOf(string userName, string groupName)
{
  using (var ctx = new PrincipalContext(ContextType.Domain))
  using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName))
  using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, userName))
  {
    return userPrincipal.IsMemberOf(groupPrincipal);
  }
}

i am calling above method with values as IsUserMemberOf("domain\\username","domain\\groupname") But i see a null pointer exception because groupPrincipal is having null value.

Any help in this regard?


Solution

  • Actually my Group is in different domain than the User which I am querying for: I made below change to my program and working now.

    and i am calling like this:

    IsUserMemberOf("domain1\\username","domain2\\groupname")
    
    
    static bool IsUserMemberOf(string userName, string groupName)
    {
     using (var ctx = new PrincipalContext(ContextType.Domain,"domain1"))
     using (var groupPrincipal = GroupPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain,"domain2"), groupName))
     using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, userName))
     {
        return userPrincipal.IsMemberOf(groupPrincipal);
     }
    

    }