‘Cannot Access a closed file’ error on some files

I’m getting Cannot Access a closed file on some files when I try to upload them. I’m creating a small web app, when a user creates an account on the website, they are required to upload a file. Once they have uploaded the file, I should see it in MongoDB. The issue is some files are uploaded successfully while others create errors. This is the exact error msg from the log:

[ERROR]: Cannot access a closed file.
    ExceptionType: System.ObjectDisposedException
    StackTrace:    at System.IO.__Error.FileNotOpen()
    at System.IO.FileStream.Seek(Int64 offset, SeekOrigin origin)
    at System.Web.HttpRawUploadedContent.TempFile.GetBytes(Int32 offset, Int32 length, Byte[] buffer, Int32 bufferOffset)
    at System.Web.HttpInputStream.Read(Byte[] buffer, Int32 offset, Int32 count)
    at System.IO.BinaryReader.ReadBytes(Int32 count)

this is the httpRunTime:

<httpRuntime maxRequestLength="41943049" requestLengthDiskThreshold="153609" />

All files are below 5MB, files are either: pdf, jpeg, or png.

This is how I am reading the file:

public string addDocument(HttpPostedFile file, string typeOfDocument, int UserID, string documentID = "", int uploadedBy = 0)
    Stream stream;
    BinaryReader bReader;
    byte[] bytes;
    stream = file.InputStream;
    bReader = new BinaryReader(stream);
    bytes = bReader.ReadBytes((int)stream.Length);

The rest of the code in addInternshipDocument is about adding the file to Mongodb


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I fixed it, it had to do with the httpRunTime. My computer I had:

<httpRuntime maxRequestLength="41943049" requestLengthDiskThreshold="153609" />

but on our testing server we had different numbers. I changed our testing server’s httpRuntime to match the one on my computer.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x