I am a little confused on the pro's and con's of each. When is it good to use OpenWeb() vs RootWeb, especially in the context of a using statement.
2 Answers
You would never use RootWeb
in the context of a using
statement and OpenWeb()
isn't useful unless the URL specified in the SPSite
constructor was a sub web of the site collection in lieu of just the site collection URL.
So, you should never do this:
using (SPWeb web = site.RootWeb)
{
// do something with web
}
...and OpenWeb()
is useful in a scenario like this:
using (SPSite site = new SPSite("http://sharepointdev/subsite"))
{
// RootWeb would return the http://sharepointdev and OpenWeb() would return "subsite"
using (SPWeb web = site.OpenWeb())
{
// do something with web
}
}
...but OpenWeb()
doesn't do anything in this scenario, except create an extra SPWeb
object...use RootWeb
:
using (SPSite site = new SPSite("http://sharepointdev"))
{
// do something with site.RootWeb
}
-
What is you are creating a workflow and you don't know if it will be the main site or a subsite. Would it be wise to always go with example two in that case? Commented Aug 12, 2011 at 16:08
-
1You could, but I would probably check to see if the Url I used to create the SPSite object equals SPSite.RootWeb.Url first...if it doesn't then go with OpenWeb()...it it does then use RootWeb. Commented Aug 12, 2011 at 16:16
-
3You can find more information on the topic why you should not use SPSite.RootWeb in a using statement here: blogs.msdn.com/b/rogerla/archive/2008/10/04/… Commented Aug 13, 2011 at 6:46
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, want to share this for something interesing on 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.