Getting "Cannot access a closed file" errormessage when getting file from session
Asked Answered
L

2

13

I have a asp.net FileUpload control. I can successfully upload file to store in session, but when I am tring to get its inputstream (I'm store file in HttpPosterFile) I'm getting error

Cannot access a closed file

tr.PostedFile //<== HttpPostedFile; 
byte[] byteArray = null; 
using (var binaryReader = new BinaryReader(tr.PostedFile.InputStream)) 
{ 
    byteArray = binaryReader.ReadBytes(tr.PostedFile.ContentLength); 
}
Larrikin answered 9/12, 2013 at 10:15 Comment(1)
Would it not be better to just store the byte array of file data in session rather than the HttpPostedFile with the stream?Nucleonics
F
31

add this to your web.config file

<system.web>
  <httpRuntime useFullyQualifiedRedirectUrl="true" maxRequestLength="15360" requestLengthDiskThreshold="15360"/>
</system.web>

http://sanjaysainitech.blogspot.com/2008/12/file-upload-error-can-not-access-closed.html

Frequency answered 9/12, 2013 at 10:17 Comment(2)
Setting the RequestLengthDiskThreshold (to anything, up to MaxRequestSize) in web.config resolves the problem. Apparently ASP.Net buffers the first chunk of the input stream, then treats the stream as closed. This can happen if you set MaxRequestLength (say, 1536) but let RequestLengthDiskThreshold default. This apparently trips over some internal code, which makes it a Microsoft bug. Setting both values resolves the problem.Electrothermics
Is this can to be implement in net core?Halfwitted
I
2

Did you use using?

If yes pay attention to not close this before you put the string to the inputstream.

Incommunicative answered 9/12, 2013 at 10:18 Comment(1)
tr.PostedFile <== HttpPostedFile; byte[] byteArray = null; using (var binaryReader = new BinaryReader(tr.PostedFile.InputStream)) { byteArray = binaryReader.ReadBytes(tr.PostedFile.ContentLength); } ; That's my codeLarrikin

© 2022 - 2024 — McMap. All rights reserved.