title: System.OutOfMemoryException when reading content of a file in a Web API
body: <p>I want to send the content of file as <code>memory stream</code> to S3 bucket via Amazon Firehose. below is my attempt which works fine for small files, but I have a file of 1 GB and I am getting <code>{"Exception of type 'System.OutOfMemoryException' was thrown."}</code>. </p>
  
  <p>My code snippet:</p>
  
  <pre><code>[HttpPost]
  public async Task&lt;bool&gt; Upload()
  {
      try
      {
          var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();
          foreach (var stream in filesReadToProvider.Contents)
          {
              var fileBytes = await stream.ReadAsByteArrayAsync(); // THIS IS WHERE EXCEPTION COMES
              using (MemoryStream memoryStream = new MemoryStream(fileBytes))
              {
                  PutRecordRequest putRecord = new PutRecordRequest();
                  putRecord.DeliveryStreamName = myStreamName;
                  Record record = new Record();
                  record.Data = memoryStream;
                  putRecord.Record = record;
                  await kinesisClient.PutRecordAsync(putRecord);
              }
          }
      }
      catch (Exception e)
      {
          Console.WriteLine(e);
          throw;
      }    
      return true;
  }
  </code></pre>
  
  <p>I looked into this link <a href="https://stackoverflow.com/questions/2809514/outofmemoryexception-when-i-read-500mb-filestream">OutOfMemoryExceptoin</a> but I could not comprehend it. Please help me.</p>
  
  <p>Attempt 1:</p>
  
  <pre><code>var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();
  foreach (var stream in filesReadToProvider.Contents)
  {
      var fileByte = await stream.ReadAsStreamAsync();
      MemoryStream _ms = new MemoryStream();
      fileByte.CopyTo(_ms); // EXCEPTION HERE
      try
      {
          PutRecordRequest putRecord = new PutRecordRequest();
          putRecord.DeliveryStreamName = myStreamName;
          Record record = new Record();
          record.Data = _ms;
          putRecord.Record = record;
          await kinesisClient.PutRecordAsync(putRecord);
      }
      catch (Exception ex)
      {
          Console.WriteLine("Failed to send record to Kinesis. Exception: {0}", ex.Message);
      }
  }
  </code></pre>