Creating an SPWeb From Its Absolute URI

Posted by | Filed under ,

A collegue of mine recently asked a fairly common question for SharePoint developers getting familiar with the SharePoint API; "If I have the absolute URI of my web, how do I use it to instantiate a corresponding SPWeb object?"

You'd assume that the SPWeb would have a constructor that accepts an absolute URI, but that isn't the case. What you have to do is first create an SPSite using your URI, then call the parameterless OpenWeb() method on it.

string uri = "http://server/site/subsite/web";

//remember your "using" statements so the SPSite and SPWeb are properly disposed
using(SPSite site = new SPSite(uri))
//here, OpenWeb() opens the web corresponding to the URI passed to the SPSite constructor
using (SPWeb web = site.OpenWeb())
{
    //use your web here
}

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments