In this blog, you will see how to set the group as an owner for all the groups in a SharePoint Online site, using CSOM. Please refer to my previous article Connect To SharePoint 2013 Online Using CSOM With Console Application

Code Snippet

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Security;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Microsoft.SharePoint.Client;
  9. namespace UpdateGroupOwners
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. string userName = "[email protected]";
  16. string siteURL = "https://c986.sharepoint.com/sites/Vijai";
  17. string ownerGroupName = "Site Owners";
  18. Console.WriteLine("Enter your password.");
  19. SecureString password = GetPassword();
  20. // ClienContext - Get the context for the SharePoint Online Site
  21. using (var clientContext = new ClientContext(siteURL))
  22. {
  23. // SharePoint Online Credentials
  24. clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
  25. // Get the SharePoint web
  26. Web web = clientContext.Web;
  27. // Get all the site groups
  28. GroupCollection groupColl = web.SiteGroups;
  29. // Get the group name which has to be set as owner to all the groups
  30. Group ownerGroup = web.SiteGroups.GetByName(ownerGroupName);
  31. // Load the site group properties
  32. clientContext.Load(groupColl);
  33. // Execute the query to the server.
  34. clientContext.ExecuteQuery();
  35. // Loop through all the site groups
  36. foreach (Group group in groupColl)
  37. {
  38. // Display the group title
  39. Console.WriteLine("GroupName: " + group.Title + "-- GroupOwnerTitle: " + group.OwnerTitle);
  40. // Update the owner
  41. group.Owner = ownerGroup;
  42. group.Update();
  43. clientContext.Load(group);
  44. // Execute the query to the server.
  45. clientContext.ExecuteQuery();
  46. // Display the updated group owner title
  47. Console.WriteLine("UpdatedOwnerTitle: " + group.OwnerTitle);
  48. }
  49. Console.ReadLine();
  50. }
  51. }
  52. private static SecureString GetPassword()
  53. {
  54. ConsoleKeyInfo info;
  55. //Get the user's password as a SecureString
  56. SecureString securePassword = new SecureString();
  57. do
  58. {
  59. info = Console.ReadKey(true);
  60. if (info.Key != ConsoleKey.Enter)
  61. {
  62. securePassword.AppendChar(info.KeyChar);
  63. }
  64. }
  65. while (info.Key != ConsoleKey.Enter);
  66. return securePassword;
  67. }
  68. }
  69. }