Darien Garcia
Darien Garcia

Reputation: 11

Getting file returned using FileContentResult and writing it to a file

Right now, I have a web service (.asmx) that calls a mvc 4 controller action returning a PDF file via:

return  File(pdfBytes, "application/pdf", "Report.pdf");

And I'm getting the result in the web service like this:

 WebResponse response = request.GetResponse();
 var status = ((HttpWebResponse)response).StatusDescription;
 var dataStream = response.GetResponseStream();
 StreamReader reader = new StreamReader(dataStream);
 string responseFromServer = reader.ReadToEnd();

What I want is to write the file returned into the file system. Something like this:

byte[] responseBytes = Encoding.UTF8.GetBytes(responseFromServer);

var file = File.Create("C://Report.pdf");
file.Write(responseBytes, 0, responseBytes.Length);

But the file written has all the pages in blank.

What am I missing here?


The solution to this was to get the bytes directly from the response stream.

Like this:

var dataStream = response.GetResponseStream() ;

byte[] responseBytes;


using (var memoryStream = new MemoryStream())
{
     dataStream.CopyTo(memoryStream);
     responseBytes = memoryStream.ToArray();

     return responseBytes;
}

Upvotes: 1

Views: 4960

Answers (1)

Mattias Åslund
Mattias Åslund

Reputation: 3907

Don't use the WebResponse object for this. Use the WebClient instead. It is great for downloading binary data over http. All you need to do is replace your webservice´s code with:

var serverUrl = "http://localhost:60176/Demo/PdfFile"; //... replace with the request url

var client = new System.Net.WebClient();
var responseBytes = client.DownloadData(serverUrl);
System.IO.File.WriteAllBytes(@"c:\Report.pdf", responseBytes);

Good luck!

Upvotes: 3

Related Questions