C#从HTTP请求保存文件 [英] C# save a file from a HTTP Request

查看:704
本文介绍了C#从HTTP请求保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着去下载和从HttpWebResponse但有保存文件(不是文本文件等)的问题IM正常。

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);
MemoryStream 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)

忘了提,这是.NET 3.5的CP和我周围有HttpWebResponse类的包装类添加的OAuth等。

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.

如果您正在使用.NET 4 ,你可以使用新的CopyTo方法:

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);
}

如果你不使用.NET 4中,你所要做的复制手动:

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);
    }
}

这篇关于C#从HTTP请求保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆