天天看點

ASP.NET C# 生成靜态頁面簡單方法

//源碼是替換掉模闆中的特征字元

            string mbPath = Server.MapPath("template.html");

            Encoding code = Encoding.GetEncoding("gb2312");

            StreamReader sr = null;

            StreamWriter sw = null;

            string str = null;

            //讀取

            try

            {

                sr = new StreamReader(mbPath, code);

                str = sr.ReadToEnd();

            }

            catch (Exception ex)

                throw ex;

            finally

                sr.Close();

            //根據時間自動重命名,擴充名也可以自行修改

            string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".aspx";

            str = str.Replace("$title$", "123asdfasf");//替換Title

            str = str.Replace("$content$", "asdf2354234");//替換content

            //生成靜态檔案

                sw = new StreamWriter(Server.MapPath("htm/") + fileName, false, code);

                sw.Write(str);

                sw.Flush();

                sw.Close();

                Response.Write("恭喜<a href=htm/" + fileName + " target=_blank>" + fileName + "</a>已經生成,儲存在htm檔案夾下!");

模闆檔案template.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

    <title> $title$ 生成靜态頁的Demo</title>

    <style type="text/css">

<!--

.STYLE1 {

    font-size: 16px;

    font-weight: bold;

}

-->

    </style>

</head>

<body>

<br />

<table width="100%" border="0" bgcolor="#339900">

  <tr>

    <td height="34" align="center" bgcolor="#FFFFFF"><span class="STYLE1">$title$ </span></td>

  </tr>

    <td height="42" bgcolor="#FFFFFF"><br />

      <br />

    内容:$content$ </td>

</table>

</body>

</html>

繼續閱讀