博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

生成静态页面

Posted on 2012-07-02 16:12  moss_tan_jun  阅读(491)  评论(0编辑  收藏  举报

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;

/// <summary>
///ConvertHtmlPage 生成静态页面
/// </summary>
public class ConvertHtmlPage
{
    /// <summary>
    ///  生成HTML文件
    /// </summary>
    /// <param name="templatePath">模板路径</param>
    /// <param name="templateName">模板名称</param>
    /// <param name="htmlPath">生成HTML的路径</param>
    /// <param name="htmlName">生成HTML的名称</param>
    /// <param name="format">替换的内容</param>
    /// <returns></returns>
    public static bool CreatePage(string templatePath,string templateName, string htmlPath, string htmlName,List<string> format)
    {
        try
        {
            //读取模板文件
            StringBuilder htmltext = new StringBuilder();
            using (StreamReader sr = new StreamReader(templatePath+templateName))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    htmltext.AppendLine(line);
                }
                sr.Close();
            }         
            //替换HTML中的标记内容
            for (int i = 0; i < format.Count; i++)
            {
                htmltext.Replace("$htmlformat[" + i + "]", format[i]);
            }
            //生成HTML文件
            using (StreamWriter sw = new StreamWriter(htmlPath+htmlName, false, System.Text.Encoding.GetEncoding("GB2312")))
            {
                sw.WriteLine(htmltext);
                sw.Flush();
                sw.Close();
            }
        }
        catch (Exception ex)
        {
            return false;
        }
        return true;
    }
}