title: How to download a file from a WCF service stream?
body: <p>I'm trying to remotely download a CSV file by calling a WCF service using jQuery. Since the file doesn't actually reside on the server, I've been trying to return it as a stream. Since I use the <code>Content-Disposition</code> header, the client's browser should automatically begin downloading the file with a given filename.</p>
  
  <p>My WCF service method in C#:</p>
  
  <pre><code>[OperationContract()]
  public Stream GetCsvFile(int id)
  {
      string s = ...;
      WebOperationContext.Current.OutgoingResponse.ContentType = "text/csv";
      WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"file1.csv\"";
      return GenerateStreamFromString(s);
  }
  
  public Stream GenerateStreamFromString(string s)
  {
      MemoryStream stream = new MemoryStream();
      StreamWriter writer = new StreamWriter(stream);
      writer.Write(s);
      writer.Flush();
      stream.Position = 0;
      return stream;
  }
  </code></pre>
  
  <p>My jQuery AJAX request:</p>
  
  <pre><code>$.ajax({
      type: "POST",
      url: serviceUrl,
      cache: false,
      data: data,
      dataType: "text",
      contentType: "application/json; charset=utf-8",
      success: function() {
          // TODO...
      }
  });
  </code></pre>
  
  <p>This request completes succesfully! And I can see the correct CSV data in the response. However, it does not initiate an actual "file download" action in the browser (testing on Chrome for now) and "file1.csv" is not saved to the client's disk.</p>
  
  <p>In an old VB.NET version of the same application, the following worked in an .aspx page code-behind:</p>
  
  <pre><code>Response.Clear()
  Response.ContentType = "text/csv"
  Response.AddHeader("content-disposition", "attachment; filename="file1.csv")
  Response.Write(s)
  Response.End()
  </code></pre>
  
  <p>This would automatically initiate a file download of "file1.csv". No "Save As" dialog would even show, the file would just download immediately. It was quite cool.</p>
  
  <p>So how come it doesn't work when I try to call a WCF service with jQuery?</p>