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

Sathish Nadarajan
 
Solution Architect
April 11, 2017
 
Rate this article
 
Views
5068

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.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment