• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
nicesoft
博客园    首页    新随笔    联系   管理    订阅  订阅

模板替换

<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 "";
        }

posted @ 2011-12-06 21:49  nicesoft  阅读(291)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3