Thursday, November 17, 2011

Trying to use SPWeb object that has been closed or disposed and is no longer valid.

Are you trying to do this:

using (SPWeb spweb = SPContext.Current.Web)
    {

     ....
    }

this will give an above stated exception.

You may never close the objects SPContext.Current.Web or SPContext.Current.Site because these are the instances your sharepoint is running on. On the other hand, if you create your own instances of SPWeb or SPSite, you must dispose of them.

using (SPSite spsite = new SPSite(SPContext.Current.site.url))
    {

     using (SPWeb spweb = spsite.openweb())
    {        ....
    }

  }

There is a tool developed by microsoft (SPDisposeCheck) that checks your disposing habits and gives you a nice report of possible issues: http://archive.msdn.microsoft.com/SPDisposeCheck

You can even see the best practices of Microsoft -There is

http://msdn.microsoft.com/en-us/library/aa973248(v=office.12).aspx

 

Thanks for reading. If you have some other explanation – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

References:

http://msdn.microsoft.com/en-us/library/aa973248(v=office.12).aspx

 

No comments:

Post a Comment