模板替换
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>无标题页</title>
</head>
<body>
标题:$title<br/>
内容:$content
</body>
</html>
public static string WriteFileMethod()
{
string path = HttpContext.Current.Server.MapPath("test/");
Encoding code = Encoding.GetEncoding("gb2312");
// 读取模板文件
string temp = HttpContext.Current.Server.MapPath("templet.htm");
StreamReader sr = null;
StreamWriter sw = null;
string str = "";
try
{
sr = new StreamReader(temp, code);
str = sr.ReadToEnd(); // 读取文件
}
catch (Exception exp)
{
HttpContext.Current.Response.Write(exp.Message);
HttpContext.Current.Response.End();
sr.Close();
}
string htmlfilename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";
// 替换内容
// 这时,模板文件已经读入到名称为str的变量中了
str = str.Replace("$title", "这是个测试标题"); //模板页中的ShowArticle
str = str.Replace("$content", "这是个测试内容!");
// 写文件
try
{
sw = new StreamWriter(path + htmlfilename, false, code);
sw.Write(str);
sw.Flush();
sw.Close();
return htmlfilename;
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
sw.Close();
}
return "";
}
浙公网安备 33010602011771号