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?
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
.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.