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;
Console.WriteLine(fullSiteUrl);
site.Close();
}
}
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;
Console.Writeline(fullSiteUrl);
}
}
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.
Filed under:
SharePoint Tagged:
site collection,
site url,
SPSite