How to: Get a SPWeb object given a full URL
Posted
Thursday, February 14, 2008 4:26 PM
by
CoreyRoth
I have been using Enterprise Search lately to find sites programatically. The issue I ran into is that I needed to manipulate data on each site that was returned in the results and the only starting point I had was a fully qualified URL. At first, this task seems quite complicated because after examing the SPWeb object you will notice there is no constructor. I was hoping, I could just pass it the URL but alas that does not work. Really, the only way to create a SPWeb object is to use the SPSite object. So at first thought, I was like well how do I know what site collection something is in, given only its URL.
After a little digging in the documentation, it turns out when specifying a URL in the constructor of the SPSite object, you do not have to specify the path of the root of the site collection. You can specify the path to anything in the site collection and it will return an SPSite object representing the site collection you want. Consider the following example. I have a document at http://MyServer/MySiteCollection/MySubSite/MyDocumentLibrary/Document1.docx. In this case the site collection is at http://MyServer/MySiteCollection and the subsite is at http://MyServer/MySiteCollection. To get the SPWeb object, I start by passing the full URL of the document to the constructor of SPSite. I then just call OpenWeb with the default constructor to get the SPWeb object I need.
using (SPSite siteCollection = new SPSite("http://MyServer/MySiteCollection/MySubSite/MyDocumentLibrary/Document1.docx"))
{
SPWeb myWeb = siteCollection.OpenWeb();
}
It turns out that the functionality of OpenWeb differs greatly depending on what was passed into the constructor of SPSite. In this case, if you call OpenWeb with no parameters, it will return the SPWeb of the site where the document exists. For more information take a look at the URL below.
http://msdn2.microsoft.com/en-us/library/ms474633.aspx