Retrieving user properties using CSOM SharePoint Online

In the previous example we retrieve only user title and email (). In this article we can Retrieving user specific properties using CSOM SharePoint Online.The below example uses the Include<TSource>(IQueryable<TSource>, []) method to specify that only the Email and Title  properties are available on each user object. If you will call  other properties, it will returns a PropertyOrFieldNotInitializedException.

using Microsoft.SharePoint.Client;
using System;
using System.Security;
 
namespace Retrievinguserproperties
{
    class Program
    {
        static string Passwords = "Password";
        static string UserName = "UserName";
        static string SiteURL = "Sub Site URL";
        static void Main(string[] args)
        {
           
            using (ClientContext clientCont = new ClientContext(SiteURL))//PWA Url
            {
                SecureString passWord2 = new SecureString();
                foreach (char c in Passwords.ToCharArray()) passWord2.AppendChar(c);
                clientCont.Credentials = new SharePointOnlineCredentials(UserName, passWord2);
 
 
                GroupCollection collGroup = clientCont.Web.SiteGroups;
                Group sGroup = collGroup.GetById(2);
                UserCollection siteUser = sGroup.Users;
 
                clientCont.Load(collUser,
                users => users.Include(
                    user => user.Title,
                    user => user.LoginName,
                    user => user.Email));

 
                clientCont.ExecuteQuery();
 
                foreach (User sUser in siteUser)
                   {
                Console.WriteLine("User: {0}  ID: {1} Email: {2} Login Name: {3}", 
                sUser.Title, sUser.Id, sUser.Email, sUser.LoginName);
                   }
               
            }
        }
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.