这篇文章主要介绍了ASP.NET静态页生成方法,主要有读取模板页、匹配替换标签与生成新HTML页等步骤,是asp.net项目开发中非常实用的技巧,需要的朋友可以参考下
本文实例讲述了ASP.NET静态页生成方法。分享给大家供大家参考。具体实现方法如下:
一、问题:
由于业务需要,得把页面按照模板页生成静态页面,所以自己就琢磨了下,写些思路,以备日后需要的时候用。
二、解决方法:
静态页生成用到最多的就是匹配跟替换了,首先得读取模板页的html内容,然后进行你自己定义的标签匹配,比如说我要把我定义的标题标签换成读取数据库的标题内容,那么可以直接读取数据库的标题,然后直接进行替换,然后生成html文件就OK了。
具体代码如下:
///
/// HTML
/// 返回替换后的HTML
public static string ReturnHtml(string html)
{
string newhtml = html;
newhtml = newhtml.Replace(“”, “这个是标题替换”);//替换标题
//newhtml = newhtml.Replace(“”, “这个是内容替换”);//替换标题
newhtml = CreateList(newhtml);
return newhtml;
}
///
///
/// html文件的相对路径
/来源gaodai#ma#com搞*!代#%^码网// 返回html
public static string ReadHtmlFile(string temp)
{
StreamReader sr = null;
string str = “”;
try
{
sr = new StreamReader(HttpContext.Current.Server.MapPath(temp), code);
str = sr.ReadToEnd(); // 读取文件
}
catch (Exception exp)
{
HttpContext.Current.Response.Write(exp.Message);
HttpContext.Current.Response.End();
}
finally
{
sr.Dispose();
sr.Close();
}
return str;
}
///
///
/// 文件名(带相对路径路径,如:../a.html)
/// html内容(整个)
public static void writeHtml(string filmname, string html)
{
System.Text.Encoding code = System.Text.Encoding.GetEncoding(“utf-8”);
string htmlfilename = HttpContext.Current.Server.MapPath(filmname);
string str = html;
StreamWriter sw = null;
// 写文件
try
{
sw = new StreamWriter(htmlfilename, false, code);
sw.Write(str);
sw.Flush();
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
}
finally
{
sw.Close();
}
}
以上就是ASP.NET静态页生成方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!