1

Just want to clarify between the two: what web variable will hold in both cases:

SPWeb web = Site.OpenWeb();

SPWeb web = Site.RootWeb();

3 Answers 3

4

If you want to get hold of a subsite using GUID or URL (server-relative or site-relative), OpenWeb() should be used.The SPWeb returned from OpenWeb() should be manually disposed. Also,look this article for more information on OpenWeb() http://blog.falchionconsulting.com/index.php/2009/03/why-i-dont-use-openweb/.

RootWeb gives you the top most SPWeb associated with SPSite. Although, you can also get it using OpenWeb(), RootWeb is preferred as it does not require explicit disposal of SPWeb object it provides.

Example:

  using (SPSite site = new SPSite("http://yoursiteurl"))
    {
         SPWeb rootWebObj = site.RootWeb;
        // do something with site.RootWeb
        // No explicit rootWebObj dispose required
  }

and OpenWeb() is useful in a scenario like this:

using (SPSite site = new SPSite("http://yoursiteurl/subsite"))
{
    // RootWeb would return the http://siteurl and OpenWeb() would return "subsite"
    using (SPWeb web = site.OpenWeb())
    { 
        // do something with web
    }
}
1
  • You may need to change the code to get RootWeb. It shouldn't be in using statement. Mar 5, 2015 at 10:20
3

Example: Url of a site collection http://aissp2013/sites/TestSite. It has a sub site Q1 at Url http://aissp2013/sites/TestSite/Q1.

using (SPSite site = new SPSite("http://aissp2013/sites/TestSite/Q1"))
{
    SPWeb root = site.RootWeb;
    //root will conatin TestSite
    using (SPWeb web = site.OpenWeb())
    {
        // web will contain Q1
    }
}
0
1

Site.RootWeb is a property not a method, it will get the root web of the site collection. Site.OpenWeb() will open the current SPWeb where the code was executed.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.