Trying to use an SPWeb object that has been closed or disposed and is no longer valid error
I have encountered this error ("Trying to use an SPWeb object that has been closed or disposed and is no longer valid.") at 2 different location. The first time, I was trying to dispose the SPSite object that I got from SPContext.Current.Site. According to this post, you shouldn't dispose the SPSite or SPWeb object if it's from the SPContext. You can refer to some of the best practices for disposing sharepoint objects here.
So, to resolve this problem, you can either not dispose your object or you can create the SPSite/SPWeb object using a different way and dispose it later. i.e. using (SPSite site = new SPSite (siteUrl)){}.
The 2nd time that I got this error message, I didn't know what was going on and it took me a long time to find out the cause of the problem. I was using PublishingWeb.IsPublishingWeb(SPWeb) method to check if a particular web is a publishing web. After I checked and it is publishing web, I tried to update a list item and then I got this ugly error message. It was the IsPublishingWeb method that probably closes the SPWeb or invalidates it (I can't find anything about this in the MSDN. If anyone has any idea, thanks for sharing it.). To get around it, I had to get the SPWeb twice.
bool isPubWeb = false;
using (SPWeb web = site.OpenWeb(webUrl))
{
if (PublishingWeb.IsPublishingWeb(web))
{isPubWeb = true;}
}
using (SPWeb web = site.OpenWeb(webUrl))
{
//code to do stuffs
}
So, to resolve this problem, you can either not dispose your object or you can create the SPSite/SPWeb object using a different way and dispose it later. i.e. using (SPSite site = new SPSite (siteUrl)){}.
The 2nd time that I got this error message, I didn't know what was going on and it took me a long time to find out the cause of the problem. I was using PublishingWeb.IsPublishingWeb(SPWeb) method to check if a particular web is a publishing web. After I checked and it is publishing web, I tried to update a list item and then I got this ugly error message. It was the IsPublishingWeb method that probably closes the SPWeb or invalidates it (I can't find anything about this in the MSDN. If anyone has any idea, thanks for sharing it.). To get around it, I had to get the SPWeb twice.
bool isPubWeb = false;
using (SPWeb web = site.OpenWeb(webUrl))
{
if (PublishingWeb.IsPublishingWeb(web))
{isPubWeb = true;}
}
using (SPWeb web = site.OpenWeb(webUrl))
{
//code to do stuffs
}
Comments