Enumerating MOSS site collections using the object model

For an application I’m working on I needed to be able to get all site collections for a given server URL.

So for example if I had a web application at http://localhost how can I enumerate through all the site collections on that web application?

Here’s how:

First we need to create a new System.Url object and pass that to the static method Lookup on the SPWebApplication class.

Uri serverUri = new

SPWebApplication webApplication = SPWebApplication.Lookup(serverUri);

Now we have an instance of SPWebApplication we can enumerate it’s Sites collection like so:

foreach (SPSite siteCollection in webApplication.Sites)




And that’s it! Simple as it is, no SharePoint development book or google search gave me what I was looking for, I would have thought this was a very common task for most SharePoint devs.

One thought on “Enumerating MOSS site collections using the object model

  1. When I try to do this itsI am getting an error “Cannot open database “WSS_Content_80” requested by the login. The login failed. Login failed for user ‘userlogin’.

    You have any idea??

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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