How To Get All Site Urls Without Creating an SPSite object?

Let’s say you are trying to create a SharePoint admin tool that shows all site collections in the farm, then allows the user to interact with only the site collections of interest to him.

To get all the site collection Urls in the farm, you’d usually go with the following approach:

foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
    foreach (SPSite site in webApp.Sites)
        string fullSiteUrl = site.Url;

The disadvantage in using such an approach is that we have to create an SPSite object for every site collection in the farm, then close it. That’ll mean a lot of work allocating and deallocating memory. Luckily, there is a better approach to do this, shown below:

foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
    string webAppUrl = webApp.GetResponseUri(SPUrlZone.Default).AbsoluteUri; 

    foreach (string siteUrl in webApp.Sites.Names)
        string fullSiteUrl = webAppUrl + siteUrl;

This way, we don’t have to create any of the expensive SPSite objects then close them. On a small farm, that’ll help your application load faster, but on a large farm with hundreds of site collections, this approach is necessary.

You can find the full source for the SPSite ListView here. This was created as a Visual Studio 2008 project on top of SharePoint 2010 Beta, but you can easily remove the reference and add a reference to the 2007 Microsoft.SharePoint.dll.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s