title: Uploading file to server throws out of memory exception
body: <p>I am trying to implement a file upload system with asp.net web api and I am running into a problem.  I am trying to get the multipart form data into a memory stream so it can be written to either disk or blob storage depending on the service layer implementation.  The problem is it works fine for small files but I am trying to upload a file of 291 MB and it is throwing an out of memory exception. Here is the code:</p>
  
  <pre><code>if (!Request.Content.IsMimeMultipartContent())
  {
      Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "Request must be multipart.");
  }
  
  var provider = new MultipartMemoryStreamProvider();
  
  try
  {
      await Request.Content.ReadAsMultipartAsync(provider);
  
      var infoPart = provider.Contents.Where(x =&gt; x.Headers.ContentDisposition.Name.Replace("\"", string.Empty) == "fileInfo").SingleOrDefault();
      var filePart = provider.Contents.Where(x =&gt; x.Headers.ContentDisposition.Name.Replace("\"", string.Empty) == "filePart" &amp;&amp; x.Headers.ContentDisposition.FileName != null).Single();
      byte[] file = null;
  
      using (Stream stream = filePart.ReadAsStreamAsync().Result)
      {
          using (MemoryStream memory = new MemoryStream())
          {
              stream.CopyTo(memory);
              file = memory.ToArray();
          }
      }
  
      string fileContentType = filePart.Headers.ContentType.MediaType;
  
      FileDto result = _fileService.AddFileToResource(Variables);
      string uri = Url.Link("DefaultGet", new { id = result.ID });
      return Request.CreateResponse(HttpStatusCode.OK);
  </code></pre>
  
  <p>The part that throws the error is on the</p>
  
  <pre><code>await Request.Content.ReadAsMultipartAsync(provider);
  </code></pre>
  
  <p>The exact error is</p>
  
  <blockquote>
    <p>Error writing MIME multipart body part to output stream.</p>
  </blockquote>
  
  <p>with inner exception of </p>
  
  <blockquote>
    <p>Exception of type 'System.OutOfMemoryException' was thrown.</p>
  </blockquote>
  
  <p>I have tried creating a custom <code>BufferPolicySelector</code> as shown in the second answer of <a href="https://stackoverflow.com/questions/15506648/how-to-upload-a-large-file-with-asp-net-mvc4-web-api-with-progressbar">this post</a> and many other places but that doesn't seem to help at all.</p>
  
  <p>I have also added to my web.config:</p>
  
  <pre><code>&lt;httpRuntime targetFramework="4.5" maxRequestLength="307200"/&gt;
  </code></pre>
  
  <p>and</p>
  
  <pre><code>&lt;security&gt;
    &lt;requestFiltering&gt;
      &lt;requestLimits maxAllowedContentLength="367001600"/&gt;
    &lt;/requestFiltering&gt;
  &lt;/security&gt;
  </code></pre>