如何使用httpwebrequest将图像从网站拉到本地文件

Ste*_*ell 20 c# image file httpwebrequest

我正在尝试使用本地c#应用程序将一些图像从网站上拉到我本地计算机上的文件中.我正在使用下面列出的代码.我尝试过ASCII编码和UTF8编码,但最终文件不正确.有谁看到我做错了什么?当我将地址放入浏览器时,网址处于活动状态且正确并显示图像.

    private void button1_Click(object sender, EventArgs e)
    {
        HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create("http://www.productimageswebsite.com/images/stock_jpgs/34891.jpg");

        // returned values are returned as a stream, then read into a string
        String lsResponse = string.Empty;
        HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse();
        using (StreamReader lxResponseStream = new StreamReader(lxResponse.GetResponseStream()))
        {
            lsResponse = lxResponseStream.ReadToEnd();
            lxResponseStream.Close();
        }

        byte[] lnByte = System.Text.UTF8Encoding.UTF8.GetBytes(lsResponse);

        System.IO.FileStream lxFS = new FileStream("34891.jpg", FileMode.Create);
        lxFS.Write(lnByte, 0, lnByte.Length);
        lxFS.Close();

        MessageBox.Show("done");
    }
Run Code Online (Sandbox Code Playgroud)

Phi*_*off 30

好的形象:D

尝试使用以下代码:

你需要使用BinaryReader,因为图像文件是二进制数据,因此不能用UTF或ASCII编码

编辑:使用'确认

HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(
"http://www.productimageswebsite.com/images/stock_jpgs/34891.jpg");

// returned values are returned as a stream, then read into a string
String lsResponse = string.Empty;
using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse()){
   using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream())) {
      Byte[] lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
      using (FileStream lxFS = new FileStream("34891.jpg", FileMode.Create)) {
          lxFS.Write(lnByte, 0, lnByte.Length);
      }
   }
}
MessageBox.Show("done");
Run Code Online (Sandbox Code Playgroud)

  • @henchman:`using`块确保即使在出现未处理的异常时也会调用`Dispose`.这是一个不好的习惯不要在几乎所有适当的情况下使用(在其中创建实现`IDisposable`一个类的实例,仅将其分配给本地变量,并不会从创建它的方法返回它,当它的不是WCF代理实例).如果你总是使用它,你不会忘记它一两次. (2认同)

Ste*_*ell 15

好的,这是最终答案.它使用内存流作为缓冲来自reaponsestream的数据的方法.

    private void button1_Click(object sender, EventArgs e)
    {
        byte[] lnBuffer;
        byte[] lnFile;

        HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create("http://www.productimageswebsite.com/images/stock_jpgs/34891.jpg");
        using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse())
        {
            using (BinaryReader lxBR = new BinaryReader(lxResponse.GetResponseStream()))
            {
                using (MemoryStream lxMS = new MemoryStream())
                {
                    lnBuffer = lxBR.ReadBytes(1024);
                    while (lnBuffer.Length > 0)
                    {
                        lxMS.Write(lnBuffer, 0, lnBuffer.Length);
                        lnBuffer = lxBR.ReadBytes(1024);
                    }
                    lnFile = new byte[(int)lxMS.Length];
                    lxMS.Position = 0;
                    lxMS.Read(lnFile, 0, lnFile.Length);
                }
            }
        }

        using (System.IO.FileStream lxFS = new FileStream("34891.jpg", FileMode.Create))
        {
            lxFS.Write(lnFile, 0, lnFile.Length);
        }
        MessageBox.Show("done");
    }
Run Code Online (Sandbox Code Playgroud)


Lea*_*ner 5

答案的变体,使用async await 进行异步文件 I/O请参阅异步文件 I/O了解为什么这很重要。

使用 BinaryReader/Writer 下载 png 并写入磁盘

string outFile = System.IO.Path.Combine(outDir, fileName);

// Download file
var request = (HttpWebRequest) WebRequest.Create(imageUrl);

using (var response = await request.GetResponseAsync()){
    using (var reader = new BinaryReader(response.GetResponseStream())) {

        // Read file 
        Byte[] bytes = async reader.ReadAllBytes();

        // Write to local folder 
        using (var fs = new FileStream(outFile, FileMode.Create)) {
            await fs.WriteAsync(bytes, 0, bytes.Length);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

读取所有字节扩展方法

public static class Extensions {

    public static async Task<byte[]> ReadAllBytes(this BinaryReader reader)
    {
        const int bufferSize = 4096;
        using (var ms = new MemoryStream())
        {
            byte[] buffer = new byte[bufferSize];
            int count;
            while ((count = reader.Read(buffer, 0, buffer.Length)) != 0) {
                await ms.WriteAsync(buffer, 0, count);
            }
            return ms.ToArray();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)