上一篇讲了如何抓取博客中的图片到本地,而要在blogengine中正确显示这些图片,还要修改导入的博客中的图片地址.

  blogengine中的图片存放在app-data下的files中,而图片的存放规律是按照日期放在相应的文件夹中,比如现在是2011年5月,这个月份发表的博客中的图片就存放在files下的2011/5/文件夹下.

  了解了这个规律,我们就可以构造图片的存放目录,并将图片链接改为图片存放地址.

  通过前面的xml文件的操作,我们可以读出每篇博客的发表日期

datePublished = Convert.ToDateTime(xmldoc.GetElementsByTagName("post_date")[i].ChildNodes[0].Value.ToString());

这个日期的格式是xxxx-xx-xx,我们只要取得年份和月份就可以了

postyear = xmldoc.GetElementsByTagName("post_date")[i].ChildNodes[0].Value.ToString().Substring(04);
postmonth 
= xmldoc.GetElementsByTagName("post_date")[i].ChildNodes[0].Value.ToString().Substring(52);
 
if (postmonth.Substring(01== "0")
    {
        postmonth 
= postmonth.Substring(11);
    }

这样我们就可以使用获得的postyear和postmonth构造图片的存放目录

 imgfolder="images\\"+postyear+"\\"+postmonth;

注:示例中为了测试暂时将图片存放于images文件夹下

抓取图片后存放位置就是

FileStream writer = new FileStream(MapPath(imgfolder)+ "\\" + filename + "_s.jpg", FileMode.OpenOrCreate, FileAccess.Write);

代码中_s用于区分小图片与原始图片文件名

接下来还有一个重要的步骤就是替换图片地址及链接地址,这里要用到Regex.Replace这个方法

 

 MatchCollection mc = Regex.Matches(content, @"<a\s+href=""http://(?<website>.+?)/showpic.html#url=(?<url>.+?)""\s+target=""_blank"">(?<content>.+?)</a>");
  
foreach (Match m in mc)
    {
      
   replacestring = "<a href='/image.axd?picture=" + postyear + "%2f" + postmonth + "%2f" + filename + ".jpg'><img src='/image.axd?picture=" + postyear + "%2f" + postmonth + "%2f" + filename + "_s.jpg'></a>";
        

         content 
= Regex.Replace(content, m.Value, replacestring);
  }

 这里的技巧点可参考文档:

Regex.Replace的简单使用

http://kb.cnblogs.com/a/1241770/

关于Regex.Replace只替换第一个的问题

http://hi.baidu.com/lovebeast/blog/item/57ba0995a04f36067bf4809b.html

javascript正则表达式中使用变量关键字

http://www.cnblogs.com/symbol441/archive/2007/12/21/1008704.html

ASP中轻松实现变量名-值变换
http://www.syscy.com/articleview/2009-3-26/article_view_712.htm