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

54 篇文章 0 订阅
    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);  
                    }  
                }  
            }  
        }  
    }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值