title: How do I return a file stored as byte[] in ASP.NET Core?
body: <p>I've been searching for a while and while it should be simple, I just can't get it to work. Based on examples I've seen, this is where I got so far:</p>
  
  <p><strong>SomeAppService.cs</strong></p>
  
  <pre><code>public async Task&lt;FileStream&gt; Download(long? id)
  {
      var attachment = await _repository.FirstOrDefaultAsync(x =&gt; x.Id == id);
  
      var fileStream = new FileStream($"{attachment.FileName}.{attachment.FileExtension}", 
          FileMode.Create, FileAccess.Write);
      fileStream.Write(attachment.File, 0, attachment.File.Length);
  
      return fileStream;
  }
  </code></pre>
  
  <p>As it can be noticed, "FileName", "FileExtension" and "File" (which is the forementioned byte array) are stored in a database. The attachment can be any kind of file, save for banned extensions in the Upload method (not shown). Then in my controller I have:</p>
  
  <p><strong>SomeController.cs</strong></p>
  
  <pre><code>[AllowAnonymous]
  [HttpGet("Download/{id}")]
  public async Task&lt;IActionResult&gt; Download(long? id)
  {
      var fileStream = await appService.Download(id);
      return new FileStreamResult(fileStream, "application/octet-stream");
  }
  </code></pre>
  
  <p>However, when I hit the download endpoint, I end up with a file named "response", no extension, with 0 bytes.</p>
  
  <p>Resources:</p>
  
  <p><a href="https://stackoverflow.com/questions/42460198/return-file-in-asp-net-core-web-api">Return file in ASP.Net Core Web API</a></p>
  
  <p><a href="https://stackoverflow.com/questions/56093166/return-a-fileresult-from-a-byte">Return a FileResult from a byte[]</a></p>
  
  <p><a href="https://stackoverflow.com/questions/8624071/save-and-load-memorystream-to-from-a-file">Save and load MemoryStream to/from a file</a> (Response with 255 upvotes gave me de idea of how to turn a byte array into a filestream, but I don't know if that works)</p>