Get all users from SharePoint group programmatically using csom

This SharePoint csom tutorial explains, how to get all users from SharePoint group programmatically using csom (.Net managed object model) code in SharePoint Online.

We have a SharePoint group which has few users in it, the below code will display all the user’s email id in a comma-separated string.

Get all users from SharePoint group programmatically csom

We are doing everything inside a console application. We are trying to connect to a SharePoint online site from the console application. For this, we have stored the Email Address and Password inside the App. Config file.

That information we are retrieving using the below methods.

  • GetSPOAccountName()
  • GetSPOSecureStringPassword()

And then passing as a credentials inside the code.

public static string GetPortalOwnerEmail(string URL)
{
string ownerEmail = string.Empty;
using (ClientContext context = new ClientContext(URL))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
Microsoft.SharePoint.Client.Group group = context.Web.SiteGroups.GetByName(“My Custom SharePoint Group”);

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)
{
ownerEmail += usr.Email+”,”;
}

}
return ownerEmail;
}

private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings[“SPOPassword”])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}

private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings[“SPOAccount”];
}
catch
{
throw;
}
}

You may like following SharePoint csom tutorials:

The above SharePoint csom code will give all the users email address as a string separated by comma from a SharePoint group in SharePoint.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

  • >