Friday, May 3, 2013

Retrieve all site collections inside web application in SharePoint

In this post we will discuss how to retrieve all site collections presented inside a web application.

Also you can check out my previous posts on Redirect user based on browser language in SharePoint 2010, Change page layout programmatically SharePoint 2010 and Get user profile using SharePoint 2013 object model.

Here we will use SharePoint 2010 server object model to retrieve site collection list.
Below is the full code:

SPWebApplication webApplication = SPContext.Current.Site.WebApplication;

SPSiteCollection siteCollections = webApplication.Sites;

foreach (SPSite siteCollection in siteCollections)
{
    Label1.Text += siteCollection.Url + "<BR>";

    siteCollection.Close();
}

You can check out this article on SPContext class in SharePoint 2010.

This will show all the site collections one in each line.

Here the Sites property of the SPWebApplication class will return all the site collections inside the web application.

siteCollection.Close(); line is used to dispose the object. Also you can check this article to know more about SharePoint 2010 best practices.

No comments:

Post a Comment