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

C#应用正则表达式将相当路径转化为绝对路径

2010-06-22 21:10 423 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text.RegularExpressions;
public partial class Default7 : System.Web.UI.Page
{
// C#应用正则表达式将相当路径转化为绝对路径
//(来源:http://code.nontalk.com/2007/04/convert-relative-paths-to-absolute.html)
public static String ConvertRelativePathsToAbsolute(String text, String absoluteUrl)
{
String value = Regex.Replace(text,"<(.*?)(src|href)=\"(?!http)(.*?)\"(.*?)>","<$1$2=\"" + absoluteUrl + "$3\"$4>",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
// Now just make sure that there isn't a // because if
// the original relative path started with a / then the
// replacement above would create a //.
return value.Replace(absoluteUrl + "/", absoluteUrl);
}

protected void Page_Load(object sender, EventArgs e)
{
//简单例子
string url = "http://blog.csdn.net/gdjlc/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 20000;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
{
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
{
string html = reader.ReadToEnd();
html = ConvertRelativePathsToAbsolute(html, "http://blog.csdn.net/");
Response.Write(html);
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: