开发者

C# save a file from a HTTP Response

Im trying to download and save a file from a HttpWebResponse but im having problems saving the file (other than Text Files) properly.

I think its something to do with this part:

byte[] byteArray = Encoding.UTF8.GetBytes(http.Response.Content);
MemoryStrea开发者_运维百科m stream = new MemoryStream(byteArray);

Text Files work fine with the above code but when I try to save the Content to an Image file it gets corrupted. How do i write this 'string' data to an image file (and other binary files)

Forgot to mention, This is .NET CP 3.5 and I have a wrapper class around the HttpWebResponse class to add OAuth etc.


The problem is you're interpreting the binary data as text, even if it isn't - as soon as you start treating the content as a string instead of bytes, you're in trouble. You haven't given the details of your wrapper class, but I'm assuming your Content property is returning a string - you won't be able to use that. If your wrapper class doesn't let you get at the raw data from the web response, you'll need to modify it.

If you're using .NET 4, you can use the new CopyTo method:

using (Stream output = File.OpenWrite("file.dat"))
using (Stream input = http.Response.GetResponseStream())
{
    input.CopyTo(output);
}

If you're not using .NET 4, you have to do the copying manually:

using (Stream output = File.OpenWrite("file.dat"))
using (Stream input = http.Response.GetResponseStream())
{
    byte[] buffer = new byte[8192];
    int bytesRead;
    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
}


Use WebClient.DownloadFile. You can do it manually (something like this), but WebClient is the best bet for simple downloads.


Simplest way I found is:

  • Use ReadAsByteArrayAsync to get the data.
  • List item File.WriteAllBytes to save the file.

No need to loop through anything. Example in context below:

[TestClass]
public class HttpTests
{
    [TestMethod]
    public void TestMethod1()
    {
        var jsObject = (dynamic)new JObject();
        jsObject.html =  "samplehtml.html";
        jsObject.format = "jpeg";
        const string url = "https://mywebservice.com/api";

        var result =   GetResponse(url, jsObject).GetAwaiter().GetResult();
        File.WriteAllBytes($@"c:\temp\httpresult.{jsObject.format}", result);
    }

    static async Task<byte[]> GetResponse(string uri, dynamic jsObj)
    {
        var httpClient = new HttpClient();
        var load = jsObj.ToString();
        var content = new StringContent(load, Encoding.UTF8, "application/json");
        var response = await httpClient.PostAsync(uri, content);
        return await response.Content.ReadAsByteArrayAsync();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜