一尘不染

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

c#

我正在尝试使用本地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");
    }

阅读 244

收藏
2020-05-19

共1个答案

一尘不染

漂亮的图像:D

尝试使用以下代码:

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

编辑:using’ified

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");
2020-05-19