Wednesday, March 14, 2007

Details about Site Enumeration

There are a few different ways to enumerate sites through the SharePoint Object Model. One thing to keep in mind: a 'site' in OM lingo refers to a top level site. Everything else - subsites - are referred to as 'webs'.

When you create a new SharePoint site, unless you're creating a new Site Collection through SharePoint Central Administrator, you're creating a subsite on an existing site collection. This is true from the root WSS site - http://myserver - any sites created through the Site Actions menu are subsites of the root site.

So - here are some properties I use to crawl through the set of site collections & subsites.

SPSite.AllWebs - this property of the SPSite object returns the top level site as well as all of the subsites of the top level site. This is helpful if you need to get a list of all of a WSS web application's sites and subsites, say if you were doing a site specific backup or report. But since the data listed isn't hierarchical, if you want to build a site tree view not all that helpful.

SPSite.RootWeb - this returns the SPWeb object for a site. Most useful when you get a top level site and want to look at the contents of the site, not just site properties.

SPSite.RootWeb.Webs - this returns just the site collections underneath the SPSite object.

SPWeb.Webs - returns the sites immediately underneath the SPWeb site

Now, let's say you want to open up the URL http://server/sites/sc1/subsite1 using the following line of code:

SPSite parentSite = new SPSite("http://myserver/sites/SC1/SubSite1")

If you look at parentSite.Url, you'll see the URL to the site collection: http://myserver/sites/SC1, and not the Subsite you wanted. There's probably a more elegant way to do this, but what I do is use the AllWebs property then get the site relative URL ('SubSite1') as the AllWebs indexer:

String targetUrl = "http://server/sites/sc1/subsite1";
String relativeUrl = targetUrl.Replace(parentSite.Url, ""); // parentSiteUrl = http://myserver/sites/sc1
SPWeb subsiteWeb = parentSite.AllWebs[relativeUrl]; // relativeURL = 'SubSite1'

1 comment:

Mehul K Bhuva said...

Hi Steve,

I am a regular follower of your post,
what if i want to get a particular List namely Polls, which exists in the Top Level site Collection...

What code do i write for this ?