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:
this is the httpRunTime
:
All files are below 5MB, files are either: pdf, jpeg, or png.
This is how I am reading the file:
This is the code that calls addDocument:
And strDocumentID
is called in the controller:
What does the code that called addDocument
look like?
A trick I use is to add a console app to my solution whose sole purpose it to let me call methods in other projects without having to go through the website. The console project sets up everything needed such as dependency injection, database contexts, etc. It’s like the startup of the main website without the website code. It makes writing and testing of backend code super fast iteratively.
Always try to pass the minimal data structure needed, or wrap what you need in your own class, this makes it easier to use and test. For example you only use the InputStream of HttpPostedFile, so why not pass Stream instead?
This way you can write some test code and add a local document to your DB to ensure that part is working fine. You can also try to simulate errors such as disposing the stream for some reason before addDocument is called, to see if that is the cause.
EDIT:
The error mentioned is System.ObjectDisposedException,
which I thought likely, but you say it only happens for certain files. Is it consistent? Can you isolate which ones and see if there is any pattern? Also, if you could share the code that calls addDocument, and if there is anything else setup on your site that might affect how files are uploaded. Something is disposing your stream. Do the files take too long to upload?
I added more details to addDocument.
I can’t figure out which files are causing this issue. I tried uploading a jpeg file(1.14MB) this created the same error. I tried uploading a pdf file(76.KB) this created the same error. I was able to upload a small (15.4KB) png file, and a different pdf file (68.8KB).