How to Create a User Group in SharePoint Office 365 Programmatically using C# Client Side Object Model (CSOM)


Sathish Nadarajan
SharePoint MVP
Published On :   11 Apr 2017
Visit Count
Today :  4    Total :   1261
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

SharePoint Office 365 Tool
Simple & Powerful Tool for Migration, Security & Reporting. Free Trial


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.

SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Categories

Migratiin Tools for SharePoint