Check if user belongs to SharePoint group using CSOM

check if user belongs to SharePoint group using C#.Net
SharePoint deveopment training course

This SharePoint CSOM tutorial explains, how we can check if a particular user belongs to a SharePoint group or not using.Net managed object model code (csom). Here we will pass the email id of the user and the function will return if the user is presented in the group or not.

The code we are writing inside a console application where we have added the SharePoint client object model dlls and we are connecting to a SharePoint Online site.

Check if user belongs to SharePoint group using CSOM

Below is the full code, the method will take the Site URL, Group name and Email of the user. Here we are retrieving the credentials by using GetSPOAccountName(), GetSPOSecureStringPassword() to connect to SharePoint online site which has been explained in the console application.

public static bool IsUserBelongsToSharePointGroup(string siteURL, string groupName, string email)
{
bool isUserExistInGroup = false;

using (ClientContext context = new ClientContext(siteURL))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(),GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Web, w => w.Title, w => w.Url);
context.ExecuteQuery();

Microsoft.SharePoint.Client.Group group = context.Web.SiteGroups.GetByName(groupName);

context.Load(context.Web, w => w.Title);
context.Load(group, grp => grp.Title, grp => grp.Users, grp => grp.Owner);
context.ExecuteQuery();
foreach (User usr in group.Users)
{
if (email == usr.Email)
{
isUserExistInGroup = true;
break;
}
}

}
return isUserExistInGroup;
}

We can call the function like below:

bool isUserBelongsToGroup = IsUserBelongsToSharePointGroup(“https://onlysharepoint2013.sharepoint.com/sites/Bhawana/”, “Bhawana Owners”, “user1@OnlySharePoint2013.onmicrosoft.com”);

Once you run the code it will return if the user belongs to group or not. It will give result like below:

Check if user belongs to SharePoint group using CSOM
Check if user belongs to SharePoint group using CSOM

You may like following SharePoint CSOM tutorials:

Hope this SharePoint tutorial helps us to check if the user belongs to the SharePoint group using CSOM in SharePoint Online Office 365.

Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →