Reputation: 5664
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?
Upvotes: 2
Views: 4792
Reputation: 5664
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);
}
}
Upvotes: 0
Reputation: 72620
It's just means that :
groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName))
Returns a null pointer because your group is not in present in your domain. You just have to test your var ctx
, userPrincipal
and groupPrincipal
.
Upvotes: 1