How to Add a User to the Site Group Programmatically

Steps
  • Open Visual Studio in your system.
  • Select Console Applciation template and give as name .
  • Add a Microsoft.Cleint Assembly refrence file in right side refrence tab in visual studio.
  • Replace Program.cs with the source code  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.SharePoint.Client;  
  7. using System.IO;  
  8. namespace CSOMCodeSamples  
  9. {  
  10.    class Program  
  11.    {  
  12.       static void Main(string[] args)  
  13.       {  
  14.          // ClientContext - Get the context for the SharePoint Site  
  15.   
  16.          ClientContext clientContext = new ClientContext("http://servername/sites/CSOM/");  
  17.          // Get the SharePoint web  
  18.          Web web = clientContext.Web;  
  19.          User user = web.EnsureUser("Gowtham");  
  20.          // Get the specific site group by name  
  21.          Group group = web.SiteGroups.GetByName("CSOM Owners");  
  22.          // Add a user to the specific group  
  23.          group.Users.AddUser(user);  
  24.          // Execute the query to the server  
  25.          clientContext.ExecuteQuery();  
  26.       }  
  27.    }  

Hit F5 and check the output.