2

I tried to copy to a MemoryStream, like below, but without success

MemoryStream m = new MemoryStream();
Request.Files[0].InputStream.CopyToAsync(m);
ToDo(NameOfFile, m);

Forward i'm receiving this message:

An unhandled exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll

Helio Ferreira
  • 163
  • 1
  • 3
  • 11
  • Please read about using asynchronous methods in C#. Also when showing sample code make sure to follow good practice in naming variables (definitely `m` is not good descriptive name), disposing objects with `using` (see [MCVE] for more guidance). – Alexei Levenkov May 11 '16 at 17:06

3 Answers3

1

You need to await asynchronous methods, otherwise it likely finish execution way after request completed.

using(var memoryStream = new MemoryStream())
{
  await Request.Files[0].InputStream.CopyToAsync(memoryStream);
  ToDo(NameOfFile, memoryStream);
}

Note: you need to make all methods up to original action/page asynchronous too.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
1

First, you're using an async method, so you'll need to await it;

01 MemoryStream m = new MemoryStream();
02 await Request.Files[0].InputStream.CopyToAsync(m);
03 ToDo(NameOfFile, m);

Or just use CopyTo() instead. If you don't await on line 02, the work won't be finished by line 03.

Second, since the inputstream belongs to the Request, I'd bet that, once the web request is finished, everything about it is cleaned up, and your thread is trying to copy the request content too late.

Can you simply move lines 01 and 02 into the main thread of the request? Something more like;

 public Task<ActionResult> DoFileStuff() 
 {
    MemoryStream m = new MemoryStream();
    await Request.Files[0].InputStream.CopyToAsync(m);
    new Thread(DoMoreWork).Start();
 }

You get the idea - load the request stream into the memory stream before the Action Method finishes.

Steve Cooper
  • 20,542
  • 15
  • 71
  • 88
0

You need to await the task that is running CopyToAsync, otherwise it will be running whilst you are accessing the object it is populating

MemoryStream m = new MemoryStream();
await Request.Files[0].InputStream.CopyToAsync(m);
ToDo(NameOfFile, m);

Also, note that you need to .Dispose() the memory stream when you are finished with it, or wrap it in a using statement

Allan Elder
  • 4,052
  • 17
  • 19