12

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); 
}
Felix D.
  • 4,811
  • 8
  • 38
  • 72
Jaztingo
  • 570
  • 1
  • 5
  • 15
  • 4
    Would it not be better to just store the byte array of file data in session rather than the HttpPostedFile with the stream? – Paddy Dec 09 '13 at 10:19

2 Answers2

29

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

Indranil.Bharambe
  • 1,462
  • 3
  • 14
  • 25
  • 1
    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. – Suncat2000 Apr 26 '18 at 15:26
  • Is this can to be implement in net core? – toha Feb 23 '22 at 11:07
2

Did you use using?

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

Hadash
  • 228
  • 1
  • 2
  • 7
  • tr.PostedFile <== HttpPostedFile; byte[] byteArray = null; using (var binaryReader = new BinaryReader(tr.PostedFile.InputStream)) { byteArray = binaryReader.ReadBytes(tr.PostedFile.ContentLength); } ; That's my code – Jaztingo Dec 09 '13 at 10:51