Code Snippet – Programmatically Access Root Site Collection in Multi-Site Collection Heirarchy

It’s fairly common need in multi-site collection environment to access root site collection programmatically from the current sub site collection or sub site. It’s kind of ironic that one of my colleagues asked me same question while working on our multi-site collection environment this week.

To access the root site collection from the sub site or sub site collections in given web application, you have to somehow access the SPWebApplication object. It’s easy to access SPWebApplication object using SPSite object’s WebApplication property. Once you have access to the SPWebApplication object, you can access first site collection from SPWebApplication.Sites collection to get the handle of the root site collection.

From the sub site, use the following line of code to access root site collection and its URL.

string rootSiteCollectionURL = SPContext.Current.Web.Site.WebApplication.Sites[0].Url;

This entry was posted in Uncategorized. Bookmark the permalink.