In this blog, you will see how to get all the users from SharePoint Online site default owners group using CSOM in Console Application.
By default, when a new SharePoint site is provisioned default owners, members and visitors groups are created. I need to get all the users from default owners group. I have to get this information from multiple SharePoint sites for which I have created a text file (input/configuration file) that contains all the SharePoint site URL’s.
Steps Involved
Open Visual Studio (2017 or higher).
Create a console application and name it as GetUsersFromGroup.
In the NuGet Package Manager, install Microsoft.SharePointOnline.CSOM package.
Add a new text file and name it as Sites.txt. Enter all the site URLs from which owners need to be retrieved.
Replace Program.cs code with the following.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.IO;
- using System.Text;
- using System.Security;
- using System.Threading.Tasks;
- using Microsoft.SharePoint.Client;
-
- namespace GetUsersFromGroup
- {
- class Program
- {
- static void Main(string[] args)
- {
- string userName = "[email protected]";
- string password = "@@#$%^&";
- SecureString pwd = new SecureString();
- foreach (char c in password)
- {
- pwd.AppendChar(c);
- }
-
-
- string[] URLs = System.IO.File.ReadAllLines(@"C:\Users\anavi\Documents\Visual Studio 2017\Projects\GetUsersFromGroup\GetUsersFromGroup\Sites.txt");
-
- foreach (string siteURL in URLs)
- {
- Console.WriteLine(siteURL);
- GetOwners(userName, pwd, siteURL);
- }
- Console.ReadLine();
- }
-
- private static void GetOwners(string userName, SecureString pwd, string siteURL)
- {
-
- using (var ctx = new ClientContext(siteURL))
- {
-
- ctx.Credentials = new SharePointOnlineCredentials(userName, pwd);
-
- UserCollection owners = ctx.Web.AssociatedOwnerGroup.Users;
-
- ctx.Load(owners);
-
- ctx.ExecuteQuery();
-
-
- if (owners != null)
- {
-
- foreach (var owner in owners)
- {
-
-
-
- if (owner.PrincipalType.ToString() == "User" && !String.IsNullOrEmpty(owner.Email))
- {
-
- Console.WriteLine(owner.Email);
- }
- }
- }
- }
- }
- }
- }
Thus in this blog, you saw how to get all the users from SharePoint Online site default owners group using CSOM in Console Application.