Generate static page has many benefits, can alleviate the server pressure, the convenient search website search and so on, the following introduction generates the static page The instance code, has the need friend may refer to
Recently suddenly want to put the project in the news management module to make static pages, found many good articles on the Internet, here to record, now just to achieve static page generation and did not implement paging function. The main principle is to read the database data and then replace the contents of the static template page.
First make a template page, temporarily named template.htm, the sample code is as follows:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<body>
<div>
$content $
</div>
</body>
Then make a dynamic page where we use a button click event to generate a static page.
Front page main code (Default.aspx):
Copy Code code as follows:
<%@ Page language= "C #" autoeventwireup= "true" codefile= "Default.aspx.cs" inherits= "_default"%>
<! 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></title>
</head>
<body>
<form id= "Form1" runat= "Server" >
<div>
<asp:textbox id= "txtcontent" runat= "Server" height= "179px" textmode= "MultiLine" width= "350px" ></asp : textbox><br/>
<br/>
<asp:button id= "Btnmake" runat= "Server" onclick= "Btnmake_click" text= "Generate static page"/>
</div>
</form>
</body>
</html>
Background page main code (Default.aspx.cs):
Copy Code code as follows:
protected void Btnmake_click (object sender, EventArgs e)
{
//Replace the feature characters in the template
string mbpath = Server.MapPath ("template.htm");
Encoding code = encoding.getencoding ("UTF-8");
StreamReader sr = null;
StreamWriter sw = null;
string str = null;
Read
Try
{
sr = new StreamReader (Mbpath, code);
str = Sr. ReadToEnd ();
}
catch (Exception ex)
{
throw ex;
}
finally
{
Sr. Close ();
}
//automatic renaming based on time, extension can also be modified
string fileName = DateTime.Now.ToString ("yyyymmddhhmm") + ". htm";
str = str. Replace ("$content $", txtcontent.text);//replacement content
//Generate static file
Try
{
SW = new StreamWriter (Server.MapPath ("~/") + FileName, false, code);
Sw. Write (str);
SW. Flush ();
}
catch (Exception ex)
{
throw ex;
}
finally
{
SW. Close ();
Response.Write ("<a href=" + filename + "mce_href=" + filename + "target=_blank>" + filename + "</a> has been generated!" ");
}
}
When the news volume is very large, this will increase the storage pressure on the server, temporarily record the graduation design and then consider adding dynamic static page, static page paging function.