C#后台下载图片保存至某个文件夹
调用方法
Dictionary<string, string> dir = new Dictionary<string, string>();
dir.Add(filename, filepath);
downloadImage(imgpath, dir);
方法体
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);
}
}
}