Using SPFile after parent SPWeb disposed RRS feed

  • Question

  • I have a piece of code that is doing something similar to the following:

    SPFile file;

    using (SPSite site = new SPSite(url)) {
       using (SPWeb web = site.OpenWeb()) {
          file = web.GetListItem(some_url).File;

    Stream strm = file.OpenBinaryStream();
    byte[] buffer = new byte[strm.Length];

    The trouble is, sometimes the last line throws an exception when it tries to access the strm.Length property... and sometimes, it works just fine. It usually works fine for the first few calls, but calling it many times within a short period of time results in the exception. The exception is:

    Exception occurred. (Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION))

    My gut feeling is that doing the file.OpenBinaryStream() after the parent SPWeb has been disposed of is dangerous. Can anybody confirm or deny this?
    Wednesday, April 8, 2009 7:44 PM


  • My gut feeling appears to have been correct. You should not reference an SPFile instance outside of the scope of the SPWeb/SPSite from which it was obtained.
    Wednesday, May 20, 2009 7:37 PM