您的位置:首页 > 编程语言 > ASP

asp.net 怎么把远程图片保存为本地文件?

2008-08-07 21:24 676 查看
using System;

using System.Text;

using System.Text.RegularExpressions;

using System.IO;

using System.Net;

namespace BookStore.Component

{

/// <summary>

///

/// </summary>

public class DownloadUtil : System.Web.UI.Page

{

public DownloadUtil(){}

private string [] GetImgTag(string htmlStr)

{

Regex regObj = new Regex("<img.+?>",RegexOptions.Compiled|RegexOptions.IgnoreCase);

string [] strAry = new string [regObj.Matches(htmlStr).Count] ;

int i = 0;

foreach (Match matchItem in regObj.Matches(htmlStr))

{

strAry[i] = GetImgUrl(matchItem.Value);

i++;

}

return strAry ;

}

private string GetImgUrl(string imgTagStr)

{

string str = "";

Regex regObj = new Regex("http://.+?.gifhttp://.+?.jpghttp://.+?.jpeghttp://.+?.bmp",

RegexOptions.Compiled|RegexOptions.IgnoreCase);

foreach (Match matchItem in regObj.Matches(imgTagStr))

{

str = matchItem.Value;

}

return str;

}

public string SaveUrlPics(string strHTML)

{

string [] imgurlAry = GetImgTag(strHTML);

try

{

for(int i=0 ; i<imgurlAry.Length ; i++)

{

WebRequest req=WebRequest.Create(imgurlAry[i]);

string preStr=System.DateTime.Now.ToString()+"_";

preStr=preStr.Replace("-","_");

preStr=preStr.Replace(":","_");

preStr=preStr.Replace(" ","_");

WebClient wc=new WebClient();

wc.DownloadFile(imgurlAry[i],Server.MapPath("images")+"/"

+preStr+imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/")+1));

strHTML=strHTML.Replace(imgurlAry[i],"images/"

+preStr+imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/")+1));

}

return strHTML;

}

catch(Exception ex)

{

return ex.Message;

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: