Question

I want to write the following inside a c# console application:-

  1. I have a site collection http://servername/
  2. This site collection have a subsite http://servername/customers/
  3. 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:-

  1. To loop through all the subsites under the http://servername/customers/ subsite.
  2. And inside each subsite (for example /customers/A/)
  3. To get a list title = “Manager Tracking”
  4. 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

Was it helpful?

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
scroll top