Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
C# creating stream object by using statement

I have one method to download s3 file

Method

Public ActionResult download(string filename, string credentials)
{
  ....
  Using(stream res = response from s3)
  { 
       return file(res, type, filename);
   }
}

But exception is throwing on executing the above method.

Exception message - The request was aborted: The connection was closed unexpectedly

I have to release the stream 'res' object after download.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

In the case of the File method for returning an ActionResult, you are transferring responsibility for closing the stream to the action-result, so indeed you do not want to call Dispose or use using. This is so that the ActionResult does not need to buffer the data. So: just take out the using:

public ActionResult Download(string filename, string credentials)
{
  ....
  var res = /* response from s3 */
  return File(res, type, filename);
}

If you have non-trivial code, you can make it more complex:

public ActionResult Download(string filename, string credentials)
{
  ....
  Stream disposeMe = null;
  try {
      // ...
      disposeMe = /* response from s3 */
      // ...
      var result = File(disposeMe, type, filename);    
      disposeMe = null; // successfully created File result which
                        // now owns the stream, so *leave stream open*
      return result;
  } finally {
      disposeMe?.Dispose(); // if not handed over, dispose
  }
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!