[Solved] Trying to use an SPWeb Object that has been closed or disposed and is no longer valid SharePoint 2013/3016 Server Object Model

Here we will discuss how to solve error Trying to use an SPWeb Object that has been closed or disposed and is no longer valid which comes while working with SharePoint 2013/2016 server object model.

Recently I was trying to retrieve list templates using SharePoint 2016 server object model in SharePoint 2016. I was using Visual Studio 2017 and was retrieving list templates inside a visual web part for SharePoint 2016.

I was using the below SharePoint server object model code.

using (SPSite oSite = SPContext.Current.Site)
{
using (SPWeb oWeb = oSite.RootWeb.Site.OpenWeb())
{
//Below is the code
}
}

But it gave error as Trying to use an SPWeb Object that has been closed or disposed and is no longer valid, and the error looks like below:

Trying to use an SPWeb Object that has been closed or disposed and is no longer valid
Trying to use an SPWeb Object that has been closed or disposed and is no longer valid

Trying to use an SPWeb Object that has been closed or disposed and is no longer valid

The problem was coming because of the using block I was using the code.

Since I was using SPContext.Current.Site, I should not use the using block. SharePoint will do automatically memory management. It will dispose unused objects automatically.

So to resolve the issue, I modified the code like below:

SPSite oSite = SPContext.Current.Site;
   {
SPWeb oWeb = oSite.RootWeb.Site.OpenWeb();
	{
	//Below is the code
	}
   }

You may like following SharePoint server object model tutorials:

I hope this tutorial helps to resolve Trying to use an SPWeb Object that has been closed or disposed and is no longer valid error in SharePoint 2013/2016.

>