Follow in Twitter & Facebook


Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools


Friday, July 28, 2017

Retrieve all users from SharePoint group using C#.Net object model code in SharePoint online

We can retrieve all users from a SharePoint group using .Net managed object model code in SharePoint online. We have a SharePoint group which has few users in it, the below code will display all the user's email id in comma separated string.

We are doing everything inside a console application. We are trying to connect to a SharePoint online site from the console application. For this we have stored the Email Address and Possword inside the App.Config file. Those informations we are retrieving using the below methods.
GetSPOAccountName()
GetSPOSecureStringPassword()

And then passing as a credentials inside the code.

public static string GetPortalOwnerEmail(string URL)
        {
            string ownerEmail = string.Empty;
            using (ClientContext context = new ClientContext(URL))
            {
                context.AuthenticationMode = ClientAuthenticationMode.Default;
                context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
                context.Load(context.Web, w => w.ServerRelativeUrl);
                context.Load(context.Web, w => w.Title);
                context.ExecuteQuery();            
                Microsoft.SharePoint.Client.Group group = context.Web.SiteGroups.GetByName("My Custom SharePoint Group");

                context.Load(context.Web, w => w.Title);
                context.Load(group, grp => grp.Title, grp => grp.Users, grp => grp.Owner);
                context.ExecuteQuery();
                foreach (User usr in group.Users)
                {
                    ownerEmail += usr.Email+",";
                }

            }        
            return ownerEmail;
        }



     private static SecureString GetSPOSecureStringPassword()
        {
            try
            {              
                var secureString = new SecureString();
                foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
                {
                    secureString.AppendChar(c);
                }              
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {              
                return ConfigurationManager.AppSettings["SPOAccount"];
            }
            catch
            {
                throw;
            }
        }

The above code will give all the users email address as a string separated by comma.




0 on: "Retrieve all users from SharePoint group using C#.Net object model code in SharePoint online"