1.下载图片到本地
代码如下
/// <summary>
/// 编 码 人:苏飞
/// 联系方式:361983679
/// 更新网站:[url=http://www.sufeinet.com/thread-655-1-1.html]http://www.sufeinet.com/thread-655-1-1.html[/url]
/// </summary>
using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions; namespace DotNet.Utilities
{
/// <summary>
/// 图片下载
/// </summary>
public class ImageDown
{
public ImageDown()
{ } #region 私有方法
/// <summary>
/// 获取图片标志
/// </summary>
private string[] GetImgTag(string htmlStr)
{
Regex regObj = new Regex("<img.+?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
string[] strAry = new string[regObj.Matches(htmlStr).Count];
int i = ;
foreach (Match matchItem in regObj.Matches(htmlStr))
{
strAry = GetImgUrl(matchItem.Value);
i++;
}
return strAry;
} /// <summary>
/// 获取图片URL地址
/// </summary>
private string GetImgUrl(string imgTagStr)
{
string str = "";
Regex regObj = new Regex("http://.+.(?:jpg|gif|bmp|png)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
foreach (Match matchItem in regObj.Matches(imgTagStr))
{
str = matchItem.Value;
}
return str;
}
#endregion /// <summary>
/// 下载图片到本地
/// </summary>
/// <param name="strHTML">HTML</param>
/// <param name="path">路径</param>
/// <param name="nowyymm">年月</param>
/// <param name="nowdd">日</param>
public string SaveUrlPics(string strHTML, string path)
{
string nowym = DateTime.Now.ToString("yyyy-MM"); //当前年月
string nowdd = DateTime.Now.ToString("dd"); //当天号数
path = path + nowym + "/" + nowdd;
if (!Directory.Exists(path)) Directory.CreateDirectory(path); string[] imgurlAry = GetImgTag(strHTML);
try
{
for (int i = ; i < imgurlAry.Length; i++)
{
string preStr = System.DateTime.Now.ToString() + "_";
preStr = preStr.Replace("-", "");
preStr = preStr.Replace(":", "");
preStr = preStr.Replace(" ", "");
WebClient wc = new WebClient();
wc.DownloadFile(imgurlAry, path + "/" + preStr + imgurlAry.Substring(imgurlAry.LastIndexOf("/") + ));
}
}
catch (Exception ex)
{
return ex.Message;
}
return strHTML;
}
}
}