Вопрос

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

SPWeb web = Site.OpenWeb();

SPWeb web = Site.RootWeb();
Это было полезно?

Решение

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
    }
}

Другие советы

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
    }
}

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с sharepoint.stackexchange
scroll top