次の方法で共有


Do NOT Dispose SPContext.Current.Site.RootWeb

I encountered the following error in one of the visual webpart: Trying to use an SPWeb object that has been closed or disposed and is no longer valid. If user is given “Manage Web” at the root site then there is no error.

Did some research and found out the there is piece of code used by this web part has the following construct:

using (SPWeb web = SPContext.Current.Site.RootWeb)
{
   ...
}

The rule of thumbs is that do not dispose object you did not create. In the above construct, did we create the new instance of SPWeb? Let’s take a look at the RootWeb property in the SPSite class using Reflector:

image

so if the m_rootWeb is already there no instance is created.

I fixed the code by changing it to using (SPWeb web = SPContext.Current.Site.OpenWeb()) { … } and the error goes away. BUT what is the explanation of site Admin user would not have the same problem?

… I will update here if I found the answer.