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

前端 未结 4 1724
粉色の甜心
粉色の甜心 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:58

    Okay, here's the final answer. It uses a memorystream as a way to buffer the data from the 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");
        }
    

提交回复
热议问题