/// <summary>
/// 下载网页图片至指定位置
/// </summary>
/// <param name="Imgurl"></param>
/// <param name="pathname">绝对路径</param>
/// <param name="filename">文件名</param>
public static void downloadImage(string Imgurl, string pathname, string filename)
{
WebRequest request = WebRequest.Create(Imgurl);
WebResponse response = request.GetResponse();
Stream reader = response.GetResponseStream();
if (!System.IO.Directory.Exists(pathname))
{
System.IO.Directory.CreateDirectory(pathname);
}
FileStream writer = new FileStream(pathname + filename, 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();
}
实例:
public string SendTempMessage()
{
string pathname = string.Empty;
try
{
string imageUrl = "https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy96eG9MYWVDSTI4VFNHb3ZqMDRkamxINUtlUFZ3YjNzOFlDSmliQjJzTFJTSlRjdjBValcyVTdZMXQ4VllZQlIxMTVDQm9pYTJuOEJNVGNaaWNkeUlUZEVpYkEvNjQw?x-oss-process=image/format,png";
string time = DateTime.Now.ToString("yyyy-MM-dd");
string savefilename = string.Format("{0}.png", "测试图片" + DateTime.Now.Millisecond);
pathname = "D:\\LogFile\\MeiTuan_prescription\\" + time + "\\";
FileHelper.downloadImage(imageUrl, pathname, savefilename);
}
catch (Exception ex)
{
return ex.ToString();
}
return "成功:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")+ "\n 图片保存地址:"+ pathname;
}
结果: