C#下载网页图片

下载方法


public static void downloadImage(string Imgurl, Dictionary<string, string> keyValues)
        {
    
    
            foreach (var item in keyValues)
            {
    
    
                try
                {
    
    
                    Thread.Sleep(2);
                    System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);
                    WebRequest request = WebRequest.Create(Imgurl);
                    WebResponse response = request.GetResponse();
                    Stream reader = response.GetResponseStream();
                    if (!Directory.Exists(item.Value))
                    {
    
    
                        Directory.CreateDirectory(item.Value);
                    }

                    FileStream writer = new FileStream(item.Value + item.Key, FileMode.OpenOrCreate, FileAccess.Write);
                    byte[] buff = new byte[512];
                    int c = 0; //实际读取的字节数
                    while ((c = reader.Read(buff, 0, buff.Length)) > 0)
                    {
    
    
                        writer.Write(buff, 0, c);
                    }
                    writer.Close();
                    writer.Dispose();
                    reader.Close();
                    reader.Dispose();
                    response.Close();
                }
                catch (Exception ex)
                {
    
    
                    Console.WriteLine("***************保存图片报错了,错误{0}****************", ex.Message);
                }
            }
        }

调用方法

Dictionary<string, string> dir = new Dictionary<string, string>();
  			 dir.Add(filename, filepath);//filename:保存在本地时的文件名,filepath保存在本地的地址
  			 //imgpath:文件下载地址
  			 downloadImage(imgpath, dir);

猜你喜欢

转载自blog.csdn.net/qq_42455262/article/details/116191479