How to get an SPWeb object from a URL

One of the problems with SharePoint is that it’s very difficult to figure out what site is specified by a URL. After all, the URL to a particular page contains:

  • the Server
  • possibly (but not necessarily) a managed path and site collection
  • possibly (but not necessarily) a site
  • possibly (but not necessarily) a folder (such as ‘/lists/’)
  • possibly (but not necessarily) a list/library name
  • possibly (but not necessarily) a folder in a Library
  • the item itself.

Suffice to say, with all those optional bits, decomposing a URL to find the site is really hard. There is, however, a slightly obscure way of find this. You can create a site collection (SPSite) with a full URL, and then simply call OpenWeb() without any parameters to return you the site (SPWeb):

string path = "http://example/examplesite/_layouts/settings.aspx";
using (SPSite siteCollection = new SPSite(path))
using (SPWeb site = siteCollection.OpenWeb())
//Do something with the site

I found this when looking at the MSDN docs for SPSite.OpenWeb(). Check out the examples in there.

It’s a little weird that the SPSite object remembers information about how it was opened like that. But it is useful to know.

How to get an SPWeb object from a URL

5 thoughts on “How to get an SPWeb object from a URL

  1. Tracy says:

    Thanks Andy! I’ve been muddling with this topic while trying to write a subsite displayer web part for WSS 3.0 for a couple hours now. Thanks for clarifying the functionality.

  2. Andy – I would agree that its really obscure. But I hope Microsoft doesn’t fix that šŸ˜› otherwise we’ll have to use the constructor overloaded .OpenWeb(serverRelativeURL)
    Anyway thanks for the affirmation/confirmation šŸ˜‰

  3. Not sure why, but this approach doesn’t seem to be working for me. It might work when you’ve got a single SPSite and all SPWebs, but as soon as you start using managed paths and multiple site collections, this doesn’t work any longer.

  4. Yup, I’m not sure why either, but it definitely does work with multiple site collections, managed paths, and alternate access maps. I’ve been using it for that for years.

  5. Brilliant! Just what I was looking for in answer to a problem of finding a web that was buried by a managed path! Thanks very much šŸ™‚

Leave a Reply

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

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.