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
Uri(“http://localhost”);
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)
{
Console.WriteLine(siteCollection.PortalName);
}
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.