模板文件(Template.html):只是一个包含特殊字符的简单页面,仅为本事例服务.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>$Title</title>
</head>
<!-- 静态模板页面,主要是定义了一些特殊字符,用来被替换 -->
<body>
<div style="width:417px; height: 54px;">
<br />
$Title
<br />
浏览<font color="red">X</font>次 $Time
</div>
<br />
<br />
<div style="width: 100%">
$Content
</div>
<br />
<div style="width: 100%; height: 9px">
$Pager
<br />
</div>
</body>
</html>
配置文件(web.config): 路径为绝对路径
<appSettings>
<!--生成静态页面所需的设置,路径需相对路径-->
<add key="TemplateFilePath" value="%ProjectsPath%\Web\HTML\Template\Template.html"/>
<add key="NewFileSavePath" value="%ProjectsPath%\Web\HTML\"/>
<add key="Title" value="$Title"/>
<add key="Time" value="$Time"/>
<add key="Content" value="$Content"/>
<add key="Pager" value="$Pager"/>
<add key="Separator" value="|"/>
<add key="Encoding" value="gb2312"/>
</appSettings>
创建文件的类(HtmlFile.cs):
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using System.Configuration;
/// <summary>
/// 对 HTML 文件的操作
/// </summary>
public class HtmlFile
{
#region 成员变量
// 获取配置文件中的配置信息
private static readonly string templateFilePath = ConfigurationManager.AppSettings["TemplateFilePath"];
private static readonly string newFileSavePath = ConfigurationManager.AppSettings["NewFileSavePath"];
private static readonly string titleString = ConfigurationManager.AppSettings["Title"];
private static readonly string timeString = ConfigurationManager.AppSettings["Time"];
private static readonly string contentString = ConfigurationManager.AppSettings["Content"];
private static readonly string pagerString = ConfigurationManager.AppSettings["Pager"];
private static readonly string separatorString = ConfigurationManager.AppSettings["Separator"];
private static readonly string encodingString = ConfigurationManager.AppSettings["Encoding"];
#endregion
#region 构造方法
#endregion
#region 成员方法
/// <summary>
/// 使用指定的标题和内容创建 HTML 文件,
/// 文件使用的模板文件路径、保存路径、编码类型、和替换所用字符串均从配置文件中获取,
/// 如果您想更改以上信息请在配置文件中设置
/// </summary>
/// <param name="title">新文件的标题</param>
/// <param name="content">新文件的内容,如果内容需要分页请在配置文件中设置对内容拆分所用的标记,默认为 "|"</param>
/// <returns></returns>
public static bool CreateHtml( string title , string content )
{
//
return CreateHtml( templateFilePath , newFileSavePath , title , content );
}
/// <summary>
/// 使用指定的模板创建包含指定标题和内容的 HTML 文件,
/// 并在指定的路径下创建以日期为名的文件夹以保存新文件,
/// 文件使用的编码类型、和替换所用字符串均从配置文件中获取,如果您想更改以上信息请在配置文件中设置
/// </summary>
/// <param name="templateFile">模板文件的完整绝对路径</param>
/// <param name="savePath">新文件要保存的绝对路径,将在此路径下创建以日期为名的文件夹保存文件</param>
/// <param name="title">新文件的标题</param>
/// <param name="content">新文件的内容,如果内容需要分页请在配置文件中设置对内容拆分所用的标记,默认为 "|"</param>
/// <returns></returns>
public static bool CreateHtml( string templateFile , string savePath , string title , string content )
{
//
// 清除路径中的空格
templateFile = templateFile.Trim( );
savePath = savePath.Trim( );
// 分割内容以便分页
string[] contents = content.Split( separatorString.ToCharArray( ) );
string nowTime = DateTime.Now.ToString( "HHmmss" ); // 存放当前时间
// 用于存放新文件名称和内容的键值对的集合
IList<DictionaryEntry> newFileList = new List<DictionaryEntry>( );
string templateContent; // 用于存放模板文件中所有内容
string path; // 创建的文件要保存的文件路径
string filePath; // 新文件的包含文件名的完整路径
// 如果用户指定的保存路径末尾不包含 "\" 则加上
savePath = ( savePath.LastIndexOf( '\\' ) == savePath.Length - 1 ) ? savePath : ( savePath + "\\" );
// 在用户指定的路径下添加以当天日期为名称的文件夹
path = savePath + DateTime.Now.ToString( "yyyyMMdd" );
try
{
// 如果该路径不存在则创建
if ( !Directory.Exists( path ) )
{
Directory.CreateDirectory( path ); // 创建文件夹
}
using ( StreamReader sr = new StreamReader( templateFile , Encoding.GetEncoding( encodingString ) ) )
{
templateContent = sr.ReadToEnd( ); // 将模板文件中的内容读出
}
// 循环设置每页内容
for ( int i = 0 ; i < contents.Length ; i++ )
{
string newFileContent = templateContent;
newFileContent = newFileContent.Replace( titleString , title ); // 设置标题
// 设置时间
newFileContent = newFileContent.Replace( timeString , DateTime.Now.ToLongDateString( ) + " " + DateTime.Now.ToLongTimeString( ) );
newFileContent = newFileContent.Replace( contentString , contents[i] ); // 设置内容
// 如果只有一页,就直接以当前时间为文件名保存
if ( contents.Length == 1 )
{
// 将分页设置为空
newFileContent = newFileContent.Replace( pagerString , "" );
// 以当前时间命名的无序号文件名
filePath = string.Format( "{0}\\{1}.htm" , path , nowTime );
}
else// 否则就添加序号保存,如 080808.htm、080808_1.htm、080808_2.htm
{
StringBuilder pages = new StringBuilder( );
// 如果不是第一页,加入"上一页"导航
if ( i != 0 )
{
// 如果是第二页,"上一页"链接中无序号,因为第一页的文件名中无序号 如链接为 080808.htm
if ( i == 1 )
{
pages.Append( string.Format( "<a href='{0}.htm'><img src='http://www.cnblogs.com/Images/Buttons/6787033.gif' alt='浏览上一页' align='absmiddle'></a> " , nowTime ) );
}
else//否则有序号 如:080808_1.htm
{
pages.Append( string.Format( "<a href='{0}_{1}.htm'><img src='http://www.cnblogs.com/Images/Buttons/6787033.gif' alt='浏览上一页' align='absmiddle'></a> " , nowTime , i - 1 ) );
}
}
// 循环添加数字导航
for ( int j = 1 ; j <= contents.Length ; j++ )
{
// 如果数字代表当前页则不加超链接
if ( j - 1 == i )
{
pages.Append( string.Format( "[{0}] " , j ) );
}
else if ( j == 1 )
{
pages.Append( string.Format( "<a href='{0}.htm'>[{1}]</a> " , nowTime , j ) );
}
else
{
pages.Append( string.Format( "<a href='{0}_{1}.htm'>[{2}]</a> " , nowTime , j - 1 , j ) );
}
}
// 如果不是最后一页,加入"下一页"导航
if ( i + 1 != contents.Length )
{
pages.Append( string.Format( "<a href='{0}_{1}.htm'><img src='http://www.cnblogs.com/Images/Buttons/6787027.gif' alt='浏览下一页'></a>" , nowTime , i + 1 ) );
}
// 设置分页导航
newFileContent = newFileContent.Replace( pagerString , pages.ToString( ) );
// 如果是第一页文件名中无序号
if ( i == 0 )
{
filePath = string.Format( "{0}\\{1}.htm" , path , nowTime );
}
else
{
filePath = string.Format( "{0}\\{1}_{2}.htm" , path , nowTime , i );
}
}
// 将文件名与内容加入键值对的集合
newFileList.Add( new DictionaryEntry( filePath , newFileContent ) );
}
}
catch ( Exception ex )
{
// 如果发生异常则直接返回,不创建任何文件
throw ex;
}
try
{
// 循环创建所有文件
foreach ( DictionaryEntry newFile in newFileList )
{
// 创建新文件并将内容写入
using ( StreamWriter sw = new StreamWriter( Convert.ToString( newFile.Key ) , false , Encoding.GetEncoding( encodingString ) ) )
{
sw.Write( Convert.ToString( newFile.Value ) );
sw.Flush( );
}
}
}
catch ( IOException ex )
{
throw ex;
}
return true;
}
#endregion
}
测试页面(HtmlTest.aspx & HtmlTest.aspx.cs):
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HtmlTest.aspx.cs" Inherits="HtmlTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>CreateHtmlTest</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblTitle" runat="server" Text=" 标 题:" Font-Names="新宋体" Font-Size="Small"></asp:Label>
<asp:TextBox ID="txtTitle" runat="server" Font-Names="新宋体" Font-Size="Small"></asp:TextBox>
<br />
<asp:Label ID="lblContent" runat="server" Text=" 内 容:" Font-Names="新宋体" Font-Size="Small"></asp:Label>
<br />
<asp:TextBox ID="txtContent" runat="server" Font-Names="新宋体" Font-Size="Small" Height="359px" TextMode="MultiLine" Width="752px"></asp:TextBox><br />
<asp:Button ID="btnAdd" runat="server" Text=" 添 加 " Font-Names="新宋体" Font-Size="Small" OnClick="btnAdd_Click" /></div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class HtmlTest : System.Web.UI.Page
{
protected void Page_Load( object sender , EventArgs e )
{
}
protected void btnAdd_Click( object sender , EventArgs e )
{
string title = this.txtTitle.Text;
string content = this.txtContent.Text;
if ( string.IsNullOrEmpty( title ) || string.IsNullOrEmpty( content ) )
{
Page.RegisterStartupScript( null , "<script>alert('请填写完整')</script>" );
return;
}
if ( HtmlFile.CreateHtml( title , content ) )
{
Page.RegisterStartupScript( null , "<script>alert('创建成功!!!')</script>" );
this.txtTitle.Text = "";
this.txtContent.Text = "";
}
else
{
Page.RegisterStartupScript( null , "<script>alert('创建失败!!!')</script>" );
}
}
}
浙公网安备 33010602011771号