Sunday, June 5, 2016

Retrieve My sites list in SharePoint online

When i was working on branidng for my sites, then i should get the list of my sites so that i can apply the custom branding to all the my sites.
So, in order to get the list of my sites, i have written the below code.

private static void GetMySites()
        {
            string siteUrl = "<root my site url>";
            string userName = "<Enter tenant admin user name>";
            string password = "<Enter tenant admin password>";

            SecureString securePassword = new SecureString();
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }

            using (ClientContext clientContext = new ClientContext(siteUrl))
            {
                clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);

                Web web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQuery();

                List<SiteEntity> mysites = web.MySiteSearch();

                Console.WriteLine("My sites count: " + mysites.Count);

                string filePath = "D:\\GetMySites\MySites.txt";
                if (!System.IO.File.Exists(filePath))
                {
                    System.IO.File.Create(filePath).Close();
                }

                StringBuilder sbSites = new StringBuilder();
                using (System.IO.TextWriter writer = System.IO.File.CreateText(filePath))
                {
                    foreach (SiteEntity site in mysites)
                    {
                        sbSites = sbSites.Append(site.Url + ";");
                    }
                    writer.WriteLine(sbSites);
                }
            }
        }


Hope this code helps you to get the list of my sites in a text file.

Happy coding :)

No comments:

Post a Comment