How to use httpwebrequest to pull image from website to local file

前端 未结 4 1719
粉色の甜心
粉色の甜心 2020-11-27 07:29

I\'m trying to use a local c# app to pull some images off a website to files on my local machine. I\'m using the code listed below. I\'ve tried both ASCII encoding and UTF

4条回答
  •  一向
    一向 (楼主)
    2020-11-27 07:59

    nice image :D

    try using the following code:

    you needed to use a BinaryReader, 'cause an image file is binary data and thus not encoded in UTF or ASCII

    edit: 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");
    

提交回复
热议问题