日期:2014-05-17  浏览次数:20829 次

C#生成静态页面的方法

C#生成静态页面的方法

以下是C#生成静态页面的一种方法

   private bool CreateHl(string strtext, string strcontent, string author)
{
string yearstring = DateTime.Now.Year.ToString();
string monthstring = DateTime.Now.Month.ToString();
string daystring = DateTime.Now.Day.ToString();
string filename = yearstring + monthstring + daystring + DateTime.Now.Millisecond.ToString() + ".html";
Directory.CreateDirectory(Server.MapPath("" + yearstring + "//" + monthstring + "//" + daystring + ""));
Encoding code = Encoding.GetEncoding("gb2312");
string temp = Server.MapPath("test.htm");
Response.Write(temp);
//Response.End();
StreamReader sr = null;
StreamWriter sw = null;
string str = "";
try
{
sr = new StreamReader(temp, code);
str = sr.ReadToEnd();
}
catch (Exception exp)
{
Response.Write(exp.Message);
Response.End();
sr.Close();
}
strcontent += strcontent.Replace("\n", "<br>");
strcontent += strcontent.Replace("\r", "<br>");
str = str.Replace("{pagetitle}", strtext);
str = str.Replace("{title}", strtext);
str = str.Replace("{content}", strcontent);
str = str.Replace("{author}", author);
try
{
//sw=new StreamWriter(str,code);
// sw.WriteLine
sw = new StreamWriter(Server.MapPath("" + yearstring + "//" + monthstring + "//" + daystring + "//" + filename + ""), false, code);
//sw.Write;
sw.Write(str);
sw.Flush();
}
catch (Exception exp)
{
HttpContext.Current.Response.Write(exp);
HttpContext.Current.Response.End();

        }
finally
{
sw.Close();
}
msg.Text = filename;
return true;
}

 

 

以下是用法protected void Button2_Click(object sender, EventArgs e)
{
string title = txttitle.Text;
string content = txtcontent.Text;
string zuozhe = txtzuzhe.Text;
bool sc;
sc = CreateHl(title, content, zuozhe);
if (sc)
{
Response.Write("HTML生成成功!");

}
else
{
Response.Write("HTML生成失败!");
}

}