How to get all the Sub-Sites under a SharePoint Site Collection (C#)?

Here is the C# code for getting current site + all the sites under under current site collection.
For example, here is my site structure:


And the output will be as sown below:
URLTitle
Root Site urlRoot Site Title
Sub-site1 urlRoot Site Title>Sub-site1 title
Sub-site1.1 urlRoot Site Title>Sub-site1 title>Sub-site1.1 title
Sub-site2 urlRoot Site Title>Sub-site2 title

Here is the code:
                        SPWeb web = SPContext.Current.Web;
                        Dictionary<string, string> AllSubsites = new Dictionary<string, string>();
                        SPSecurity.RunWithElevatedPrivileges(delegate ()
                        {
                            using (SPSite ElevatedSite1 = new SPSite(web.Site.ID))
                            {
                                using (SPWeb ElevatedWeb = ElevatedSite1.OpenWeb(web.ID))
                                {
                                    string title = "";
                                    string url = "";
                                    title = ElevatedWeb.Title;
                                    url = ElevatedWeb.Url;
                                    //Console.WriteLine("" + title + " " + url);
                                    AllSubsites.Add(url, title);
                                    GetSubWeb(AllSubsites, ElevatedWeb, ElevatedWeb.Title);
                                }
                            }
                        });
                        foreach (KeyValuePair<string, string> item in AllSubsites)
                        {
                            Console.WriteLine(item.Key + " | " + item.Value);
                        }


        private static void GetSubWeb(Dictionary<string, string> subwebs, SPWeb web1, string parentTitle)
        {
            SPWebCollection webs2 = web1.Webs;
            foreach (SPWeb web2 in webs2)
            {
                string title = parentTitle + ">" + web2.Title;
                string url = web2.Url;
                //Console.WriteLine("" + title + " " + url);
                subwebs.Add(url, title);
                GetSubWeb(subwebs, web2, title);
            }
        } 

Output:


Thank you :)

Comments

Popular posts from this blog

SharePoint Online (O365) OAuth Authentication | Authorizing REST API calls against SharePoint Online Site | Get Access token from SharePoint Online | Set up OAuth for SharePoint Online Office 365

SharePoint 2013 REST API Reference

Simple Risk Assessment Matrix table with resultant risk calculation

Kendo UI (Core JavaScript) grid Server Paging, Server Sorting and Server Filtering with Dynamic SQL queries

Sharepoint- Using an Image From formatmap32x32.png in a Ribbon Control