In this article, let us see how to create a User Group Programmatically in SharePoint Office 365 using C# CSOM.
The code base is very straight forward.
namespace Console.Office365
{
using Microsoft.SharePoint.Client;
class Program
{
static void Main(string[] args)
{
CreateUserGroup();
}
public static void CreateUserGroup()
{
OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
string siteUrl = "https://******.sharepoint.com/sites/communitysite";
string userName = "Sathish@*******.onmicrosoft.com";
string password = "***********";
using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.Load(web.SiteGroups);
clientContext.Load(web.RoleDefinitions);
clientContext.ExecuteQueryRetry();
// Create a New User Group
GroupCreationInformation grp = new GroupCreationInformation();
grp.Title = "MyCustomUserGroup";
grp.Description = "This is a custom group created using the client object model";
Group newgrp = clientContext.Web.SiteGroups.Add(grp);
// Get the Role Definition (Permission Level)
var customFullControlRoleDefinition = web.RoleDefinitions.GetByName("MyPermissionLevel");
clientContext.Load(customFullControlRoleDefinition);
clientContext.ExecuteQuery();
// Add it to the Role Definition Binding Collection
RoleDefinitionBindingCollection collRDB = new RoleDefinitionBindingCollection(clientContext);
collRDB.Add(web.RoleDefinitions.GetByName("MyPermissionLevel"));
// Bind the Newly Created Permission Level to the new User Group
web.RoleAssignments.Add(newgrp, collRDB);
clientContext.Load(newgrp);
clientContext.ExecuteQuery();
}
}
}
}
Happy Coding,
Sathish Nadarajan.
Leave a comment