Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


Cannot access a closed file error at PostedFile.SaveAs
In an asynchronous thread, was calling PostedFile.SaveAs(filename).

It worked fine in debug mode when I stepped through it.

However, once published to the server, it started returning "Cannot access a closed file" errors.

Issue: If the file is over about 80 KB, the .NET 2.0 file control will buffer it to disk instead of to memory.

The error occurs because if you redirect to a new URL in your main thread (which may not happen if you are in debug mode and stopped to debug your async thread), the old response is closed, and the posted file loses its pointer to the buffered file data it was building.

One often suggested workaround on google is to set requestLengthDiskThreshold to a really large value in the web.config. This holds the file in memory and disk errors won't matter; even if the response is lost, the http posted file still has its data in memory.

However, that is NOT a good solution; you have effectively turned off buffering. Really large files will use up memory when uploading.

Instead, you should call PostedFile.SaveAs in your main Synchronous thread, saving the file to a temporary folder. Then, in your asynchronous thread, you can process and eventually delete the file.

Created By: amos 10/1/2014 3:17:46 PM
Updated: 10/1/2014 3:19:46 PM