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";
try
{
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.






