程序代码
using System;
using System.Web;
using System.IO;
using System.Text;
/// <summary>
/// Summary description for CreatHTML
/// </summary>
public class CreatHTML
{
public CreatHTML()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// 生成模板静态页方法
/// </summary>
/// <param name="fileName">HTML文件名称</param>
/// <param name="templateParams">参数数组,参数为: 标签名称|替换内容</param>
/// <returns></returns>
public static bool WriteHtmlFile(string fileName,params string[] templateParams)
{
bool succeed = false;
string[] tempArray = null;
if (string.IsNullOrEmpty(fileName))
{
return (succeed);
}
if (templateParams.Length < 1)
{
return (succeed);
}
string sTime = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);
//string path = HttpContext.Current.Server.MapPath("/" + sTime + "/");
string path = @"E:\work\web\CSharp\WebTry\" + sTime + "\\";
string addtime = DateTime.Now.ToString();
Encoding code = Encoding.GetEncoding("gb2312");
// 读取模板文件
//string temp = HttpContext.Current.Server.MapPath("/template/template.html");
string temp = @"E:\work\web\CSharp\WebTry\template.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();
}
//html文件名称
string htmlFileName = fileName + ".html";
//取出参数
for (int i = 0; i < templateParams.Length; i++)
{
tempArray = templateParams[i].Split('|');
if (tempArray.Length != 2)
{
return (succeed);
}
// 替换内容
str = str.Replace(tempArray[0], tempArray[1]);
}
// 写文件
if (!System.IO.Directory.Exists(path))//不存在路径
{
try
{
System.IO.Directory.CreateDirectory(path);
sw = new StreamWriter(path + htmlFileName, false, code);
sw.Write(str);
sw.Flush();
succeed = true;
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
}
finally
{
sw.Close();
}
}
else//存在路径
{
try
{
sw = new StreamWriter(path + htmlFileName, false, code);
sw.Write(str);
sw.Flush();
succeed = true;
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
}
finally
{
sw.Close();
sr.Close();
}
}
return (succeed);
}
}