How to loop through all subsites under a subsite using SharePoint server object model
-
10-12-2020 - |
Question
I want to write the following inside a c# console application:-
- I have a site collection
http://servername/
- This site collection have a subsite
http://servername/customers/
- And inside the customers sub site I have multiple subsites such as;
/customers/A/
,/customers/B/
, etc.
Now I want to do the following loops:-
- To loop through all the subsites under the
http://servername/customers/
subsite. - And inside each subsite (for example
/customers/A/
) - To get a list title = “Manager Tracking”
- And loop through all the items under the “Manager Tracking” list?
Can anyone advice how I can perfume this using SharePoint server-side object model? The problem I am facing is that I am unable to do the following to start from the http://servername/cusotmers/
subsite:-
SPWeb subsite = new SPWeb(“http://servername/cusotmers/”)
Where I will get this error:-
Microsoft.SharePoint.SPWeb' does not contain a constructor that takes 1 arguments
Thanks
Solution
You can use the code as below:
using(SPSite site = new SPSite("http://servername/")) //site collection url
{
using(SPWeb web = site.OpenWeb("customers")) //specific subsite url
{
SPWebCollection subWebs = web.Webs; //get all sites under specific subsites
foreach (SPWeb subSite in subWebs)
{
SPList managerList = subSite.Lists.TryGetList("Manager Tracking");
foreach (SPListItem item in managerList.Items)
{
//your logic
}
subSite.Close();
}
}
}
OTHER TIPS
If you are using Site collection Object then It will traverse through all sub sites.
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList("ListName");
try
{
if (list != null)
{
SPQuery query = new SPQuery();
query.Query = "<Where>" +
"<Contains>" +
"<FieldRef Name='Title' />" +
"<Value Type='Text'>" + keyWord + "</Value>" +
"</Contains>" +
"</Where>";
SPListItemCollection items = list.GetItems(query);
if (items != null && items.Count > 0)
{
foreach (SPItem item in items)
{
var Title = item["Title"] != null ? item["Title"].ToString() : string.Empty;
}
}
}
}
catch{}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange