.net生成html文件...
时间:2010-08-05 来源:xiaocai06
/// <summary>
/// 生成HTML文件的方法,采用的是模板替换的方法生成
/// </summary>
/// <param name="News_Title">新闻标题</param>
/// <param name="PubDate">发布日期</param>
/// <param name="Click_Count">点击次数</param>
/// <param name="News_Content">新闻内容</param>
/// <param name="Type_Title">新闻类别【新闻类别读取的是类别表,有多个】</param>
/// <param name="News_Id">新闻编号,用于生成的HTML文件的名,以新闻编号命名</param>
public void WriteFile(string News_Title, string PubDate, string Click_Count, string News_Content, string Type_Title, string News_Id)
{
string path = HttpContext.Current.Server.MapPath("../../html/");
Encoding code = Encoding.GetEncoding("gb2312");
// 读取模板文件
string temp = HttpContext.Current.Server.MapPath("html/HtmlModel.html");
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();
}
str = str.Replace("$News_Id", News_Id);
str = str.Replace("$News_Title", News_Title); //模板页中的ShowArticle
str = str.Replace("$News_Content", News_Content);
str = str.Replace("$PubDate", PubDate);
str = str.Replace("$Click_Count", Click_Count);
str = str.Replace("$Type_Title", Type_Title);
// 写文件
try
{
sw = new StreamWriter(path + News_Id + ".html", false, code);
sw.Write(str);
sw.Flush();
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
}
finally
{
sw.Close();
}
}
///传入参数调用生成HTML文件的方法
System.Random r = new Random();
string News_Id =DateTime.Now.ToString("yyyyMMhhhhmmss")+r.Next(10000000, 99999999).ToString();
string News_Title = this.LbNews_Title.Value;
string News_Content = this.LbNews_Content.Value;
string PubDate = DateTime.Now.ToString("yyyy-MM-dd");
string Type_Id = this.ddlNewsType.SelectedValue;
string Type_Title = this.ddlNewsType.SelectedItem.Text;
string OperateName = Session["UserName"].ToString();
decimal Click_Count = 0;
MNews.News_Id = News_Id;
MNews.News_Title = News_Title;
MNews.PubDate = PubDate;
MNews.Type_Id = Type_Id;
MNews.Type_Title = Type_Title;
MNews.OperateName = OperateName;
MNews.News_Content = News_Content;
MNews.Click_Count = Click_Count;
string Type= "<ul class='list_bar'>";//读取类别表 DataSet dstype = BType.GetList("1=1");
for (int j = 0; j < dstype.Tables[0].Rows.Count; j++)
{
Type += "<li><a href=../info/Index.html?Id=" + dstype.Tables[0].Rows[j]["Type_Id"].ToString() + "'>" + dstype.Tables[0].Rows[j]["Type_Title"].ToString() + "</a></li>";
}
Type =Type+ "</ul>";
int rows = BNews.Add(MNews);
if (rows > 0)
{
this.WriteFile(News_Title, PubDate, Click_Count.ToString(), News_Content, Type, News_Id);
Page.RegisterClientScriptBlock("Add", "<script>alert('保存成功');location.href='ListNews.aspx'</script>");
}
好了,大功告成,注意生成HTML文件的读取模板的路径和保存HTML文件的路径,在此我采用是将生成的HTML文件保存在网站的根目录下