How to retrive members of a specific SP security group using CSOM

sravya shivapuram 211 Reputation points
2022-05-19T18:49:20.57+00:00

Hi,

I have a requirement to retrieve the site owners for SharePoint sites using CSOM. How can I retrieve a specific security group using its name and get it's users?

Appreciate all your help. Thank you in advance.

Regards
SLS

Microsoft 365 and Office | SharePoint | Development
Microsoft 365 and Office | SharePoint | For business | Windows
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Tong Zhang_MSFT 9,261 Reputation points
    2022-05-20T05:31:40.373+00:00

    Hi @sravya shivapuram ,

    Based on my research and testing, you can following the code to get users from site group in SharePoint using CSOM:

    static void Main(string[] args)  
            {  
                var clientContext = GetonlineContext();  
                Web oweb = clientContext.Web;  
                Group oGroup = clientContext.Web.SiteGroups.GetByName("Group_Name");  
      
                // Get collection of users in the above group  
                UserCollection oUserCollection = oGroup.Users;  
      
                // Load the user collection object  
                clientContext.Load(oUserCollection);  
      
                clientContext.ExecuteQuery();  
      
                // Iterate through each User  
                foreach (User oUser in oUserCollection)  
                {  
                    Debug.WriteLine("User Name: " + oUser.Title);  
                }  
      
            }  
    

    My test result:
    203869-image.png

    More information for reference:
    https://www.codesharepoint.com/csom/get-all-users-from-site-group-in-sharepoint-using-csom


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


    0 comments No comments

  2. sravya shivapuram 211 Reputation points
    2022-05-20T19:10:55.84+00:00

    Hi @Tong Zhang_MSFT , Thank you for your response. I tried implementing this but been receiving an error saying 'Group cannot be found'. The group name looks like - 'siteID Owners' ( which is a custom owners group created as part of the site creation with that naming format) . I am trying to find the users in that 'siteID Owners' group which is visible under 'Site Permissions'. Please advise.

    Also, instead of printing it on the console, is there a way I can export this information to an excel file? Ex: The excel file needs to show 'Site Url' and 'Site Owners' information.

    Appreciate all your help and time.

    Regards
    SLS


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.