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:
URL | Title |
Root Site url | Root Site Title |
Sub-site1 url | Root Site Title>Sub-site1 title |
Sub-site1.1 url | Root Site Title>Sub-site1 title>Sub-site1.1 title |
Sub-site2 url | Root 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
Post a Comment