Method 1: send a request to the dynamic page of the server to obtain the HTML code of the page. The disadvantage of this method is obvious: slow speed. In addition, if the requested dynamic page has a verification control, the returned HTML page cannot perform data verification. However, this method is relatively simple to write. The main code is as follows:
View plaincopy to clipboardprint?
# Region // generate the static page of the requested URL
Public static void geturltohtml (string URL, string path) // The URL is the dynamic page address, and the path is the generated static page.
{
Try
{
System. net. webrequest wreq = system. net. webrequest. Create (URL );
// Get the response instance.
System. net. webresponse wresp = wreq. getresponse ();
// Get the response stream.
System. Io. Stream respstream = wresp. getresponsestream ();
// Dim reader As StreamReader = New StreamReader (respStream)
System. IO. StreamReader reader = new System. IO. StreamReader (respStream, System. Text. Encoding. GetEncoding ("gb2312 "));
String str = reader. ReadToEnd ();
System. IO. StreamWriter sw = new System. IO. StreamWriter (Path, false, System. Text. Encoding. GetEncoding ("gb2312 "));
Sw. Write (str );
Sw. Flush ();
Sw. Close ();
System. Web. HttpContext. Current. Response. Write ("<mce: script type =" text/javascript "> <! --
Alert ('page generation successful! ');
// --> </Mce: script> ");
}
Catch (System. Exception ex)
{
System. Web. HttpContext. Current. Response. Write ("<mce: script type =" text/javascript "> <! --
Alert ('page generation failed! "+ Ex. Message + "');
// --> </Mce: script> ");
}
}
# Endregion
# Region // generate the static page of the requested URL
Public static void getUrltoHtml (string Url, string Path) // The Url is the dynamic page address, and the Path is the generated static page.
{
Try
{
System. Net. WebRequest wReq = System. Net. WebRequest. Create (Url );
// Get the response instance.
System. Net. WebResponse wResp = wReq. GetResponse ();
// Get the response stream.
System. Io. Stream respstream = wresp. getresponsestream ();
// Dim reader as streamreader = new streamreader (respstream)
System. Io. streamreader reader = new system. Io. streamreader (respstream, system. Text. encoding. getencoding ("gb2312 "));
String STR = reader. readtoend ();
System. Io. streamwriter Sw = new system. Io. streamwriter (path, false, system. Text. encoding. getencoding ("gb2312 "));
Sw. Write (STR );
Sw. Flush ();
Sw. Close ();
System. Web. httpcontext. Current. response. Write ("<MCE: Script Type =" text/JavaScript "> <! --
Alert ('page generation successful! ');
// --> </MCE: SCRIPT> ");
}
Catch (system. Exception ex)
{
System. Web. HttpContext. Current. Response. Write ("<mce: script type =" text/javascript "> <! --
Alert ('page generation failed! "+ Ex. Message + "');
// --> </Mce: script> ");
}
}
# Endregion
Method 2: Read the template from the file, replace the parameters in the template, and output the file. This method is generated much faster than the first method, and the template content can be edited using tools.
Main Code:
View plaincopy to clipboardprint?
Public class Create
{
Public void CreatePage ()
{
}
Public static bool WriteFile (string strText, string strContent, string strAuthor)
{
String path = HttpContext. Current. Server. MapPath ("/test/"); // file output directory
Encoding code = Encoding. GetEncoding ("gb2312 ");
// Read the Template File
String temp = HttpContext. Current. Server. MapPath ("/template/test.html"); // template File
StreamReader sr = null;
StreamWriter sw = null;
String str = "";
Try
{
Sr = new StreamReader (temp, code );
Str = sr. ReadToEnd (); // read the file
}
Catch (Exception exp)
{
HttpContext. Current. Response. Write (exp. Message );
HttpContext. Current. Response. End ();
Sr. Close ();
}
String htmlfilename = DateTime. Now. ToString ("yyyyMMddHHmmss") + ". html"; // static file name
// Replace content
// At this time, the template file has been read into the variable named str
Str = str. Replace ("ShowArticle", strText); // ShowArticle on the template page
Str = str. Replace ("biaoti", strText );
Str = str. Replace ("content", strContent );
Str = str. Replace ("author", strAuthor );
// Write an object
Try
{
Sw = new StreamWriter (path + htmlfilename, false, code );
Sw. Write (str );
Sw. Flush ();
}
Catch (Exception ex)
{
HttpContext. Current. Response. Write (ex. Message );
HttpContext. Current. Response. End ();
}
Finally
{
Sw. Close ();
}
Return true;
}
}
/The principle is to use the class in System. IO to read and write the template file, Replace the tag in the template with Replace, and write the static html
Public class Create
{
Public void CreatePage ()
{
}
Public static bool WriteFile (string strText, string strContent, string strAuthor)
{
String path = HttpContext. Current. Server. MapPath ("/test/"); // file output directory
Encoding code = Encoding. GetEncoding ("gb2312 ");
// Read the Template File
String temp = HttpContext. Current. Server. MapPath ("/template/test.html"); // template File
StreamReader sr = null;
StreamWriter sw = null;
String str = "";
Try
{
Sr = new StreamReader (temp, code );
Str = sr. ReadToEnd (); // read the file
}
Catch (Exception exp)
{
HttpContext. Current. Response. Write (exp. Message );
HttpContext. Current. Response. End ();
Sr. Close ();
}
String htmlfilename = DateTime. Now. ToString ("yyyyMMddHHmmss") + ". html"; // static file name
// Replace content
// At this time, the template file has been read into the variable named str
Str = str. Replace ("ShowArticle", strText); // ShowArticle on the template page
Str = str. Replace ("biaoti", strText );
Str = str. Replace ("content", strContent );
Str = str. Replace ("author", strAuthor );
// Write an object
Try
{
Sw = new streamwriter (path + htmlfilename, false, Code );
Sw. Write (STR );
Sw. Flush ();
}
Catch (exception ex)
{
Httpcontext. Current. response. Write (ex. Message );
Httpcontext. Current. response. End ();
}
Finally
{
Sw. Close ();
}
Return true;
}
}
// The principle is to use the class in system. Io to read and write the template file, replace the tag in the template with replace, and write the static html
Method 3: if a large number of files are generated, the second method reads the template content repeatedly. In this case, you can use the third method-directly write your template in the Code:
View plaincopy to clipboardprint?
/// <Summary>
/// Custom Public Functions
/// </Summary>
Public class myfun
{
# Region // definition template page
Public static string SiteTemplate ()
{
String str = "";
Str + = "..."; // template page html code
Return str;
}
# Endregion
Public static bool WriteFile (string strText, string strContent, string strAuthor)
{
String path = HttpContext. Current. Server. MapPath ("/test/"); // file output directory
Encoding code = Encoding. GetEncoding ("gb2312 ");
StreamWriter sw = null;
String str = SiteTemplate (); // read the html code of the template page
String htmlfilename = DateTime. Now. ToString ("yyyyMMddHHmmss") + ". html"; // static file name
// Replace content
Str = str. Replace ("ShowArticle", strText );
Str = str. Replace ("biaoti", strText );
Str = str. Replace ("content", strContent );
Str = str. Replace ("author", strAuthor );
// Write an object
Try
{
Sw = new StreamWriter (path + htmlfilename, false, code );
Sw. Write (str );
Sw. Flush ();
}
Catch (Exception ex)
{
HttpContext. Current. Response. Write (ex. Message );
HttpContext. Current. Response. End ();
}
Finally
{
Sw. Close ();
}
Return true;
}
}
/// <Summary>
/// Custom Public Functions
/// </Summary>
Public class myfun
{
# Region // definition template page
Public static string sitetemplate ()
{
String STR = "";
STR + = "..."; // template page HTML code
Return STR;
}
# Endregion
Public static bool writefile (string strtext, string strcontent, string strauthor)
{
String Path = httpcontext. Current. server. mappath ("/test/"); // file output directory
Encoding code = encoding. getencoding ("gb2312 ");
Streamwriter Sw = NULL;
String STR = sitetemplate (); // read the HTML code of the template page
String htmlfilename = DateTime. Now. ToString ("yyyyMMddHHmmss") + ". html"; // static file name
// Replace content
Str = str. Replace ("ShowArticle", strText );
Str = str. Replace ("biaoti", strText );
Str = str. Replace ("content", strContent );
Str = str. Replace ("author", strAuthor );
// Write an object
Try
{
Sw = new StreamWriter (path + htmlfilename, false, code );
Sw. Write (str );
Sw. Flush ();
}
Catch (Exception ex)
{
HttpContext. Current. Response. Write (ex. Message );
HttpContext. Current. Response. End ();
}
Finally
{
Sw. Close ();
}
Return true;
}
}
The generation speed is from slow to fast, and the ease of operation is from simple to complex. Select an appropriate method based on the actual situation.
[Collection]:
View plaincopy to clipboardprint?
Protected override void render (htmltextwriter writer)
{
System. Io. stringwriter html = new system. Io. stringwriter ();
System. Web. UI. htmltextwriter Tw = new system. Web. UI. htmltextwriter (HTML );
Base. Render (TW );
System. Io. streamwriter SW;
Sw = new System. IO. StreamWriter (Server. MapPath ("default.html"), false, System. Text. Encoding. Default );
Sw. Write (html. ToString ());
Sw. Close ();
Tw. Close ();
Response. Write (html. ToString ());
}
Protected override void Render (HtmlTextWriter writer)
{
System. IO. StringWriter html = new System. IO. StringWriter ();
System. Web. UI. HtmlTextWriter tw = new System. Web. UI. HtmlTextWriter (html );
Base. Render (tw );
System. IO. StreamWriter sw;
Sw = new System. IO. StreamWriter (Server. MapPath ("default.html"), false, System. Text. Encoding. Default );
Sw. Write (html. ToString ());
Sw. Close ();
Tw. Close ();
Response. Write (html. ToString ());
}
View plaincopy to clipboardprint?
There are two methods to generate static pages using ASP. NET: Hard encoding in the background using C #, and reading template files using string replacement. The first method has a large amount of coding and is difficult to maintain. I will focus on the second method. The basic idea of the second method is to use tools such as DW to generate a static page template. Read the template file, replace the special tags with actual data, and generate an HTML file.
Please refer to the code
1. C #
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Xml;
Using System. IO;
Namespace htmlWeb
{
Public class CreateHtm
{
Private string fileName;
Public String FileName
{
Get {return fileName ;}
}
/** // <Summary>
/// Read the configuration file
/// </Summary>
/// <Param name = "dirname"> path name of the configuration file </param>
/// <Param name = "tag"> tag name in the configuration file </param>
/// <Returns> _ replacestr length </returns>
Private int getconfig (string dirname, string tag)
{
Xmldatadocument Config = new xmldatadocument ();
Try
{
Config. Load (dirname );
}
Catch (exception ex)
{
Throw ex;
}
Xmlnodelist list = config. getelementsbytagname (TAG );
Return list. Count;
}
/** // <Summary>
/// Generate an HTML file
/// </Summary>
/// <Param name = "configFileName"> path name of the configuration file </param>
/// <Param name = "configTag"> tag name in the configuration file </param>
/// <Param name = "dir"> path of the folder where the file is generated </param>
/// <Param name = "templateFile"> path of the template file </param>
/// <Param name = "param"> string array to be replaced </param>
/// <Returns> generated file name </returns>
Public void MakeHtml (String configFileName, String configTag, String dir, String templateFile, String [] param)
{
FileName = null;
Int count = GetConfig (configFileName, configTag );
String [] _ replacestr = new string [count];
Try
{
Filestream tfile = file. Open (templatefile, filemode. Open, fileaccess. Read );
Streamreader reader = new streamreader (tfile, encoding. getencoding ("gb2312 "));
Stringbuilder sb = new stringbuilder (reader. readtoend ());
Reader. Close ();
For (INT I = 0; I <count; I ++)
{
SB. Replace ("$ repalce [" + I + "] $", Param [I]);
}
Filename = datetime. Now. tofiletime (). tostring () + ". htm ";
FileStream rFile = File. Create (dir + "/" + fileName );
StreamWriter writer = new StreamWriter (rFile, Encoding. GetEncoding ("gb2312 "));
Writer. Write (sb. ToString ());
Writer. Flush ();
Writer. Close ();
}
Catch (Exception ex)
{
Throw ex;
}
}
Public void DeleteHtml (String dirName)
{
File. Delete (dirname );
}
}
}
Private int getconfig (string dirname, string tag) This method is used to read the configuration file (see later). It is mainly used to obtain the number of strings to be replaced. In this class, it is represented as a string array.
Public void makehtml (string configfilename, string configtag, string Dir, string templatefile, string [] PARAM) This method is used to generate static pages
Create an array of characters in Row 3. The length of the array is the number of nodes in the configuration file. Lines 5-58 read the template file and generate a stringbuilder object using the HTML code of the template file. Line 59-62 Replace the labeled "$ repalce [I] $" with the repalce () method of the stringbuilderd object as the actual data
64 rows generate a unique file name (to prevent overwriting) lines 66-70 write the new string to the file. In this way, a static file is generated.
The following is an example:
An article management system uses this class to generate static pages.
First, create a configuration file config. xml. This file tells users the meaning of each tag. As follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<HtmlWeb version = "1">
<Config>
<Article key = "0" value = "title"/>
<Article key = "1" value = "author"/>
<Article key = "2" value = "context"/>
<Aritcle key = "3" value = "date"/>
</Config>
</HtmlWeb>
After this configuration, the class will replace the positions marked with arrays 0, 1, and 2 with the question, author, content, and release date respectively.
View template files
1 2 <title> template file </title>
3 4 <body>
5 6 <li> title: $ Replace [0] $ </LI>
7 <li> author: $ Replace [1] $ </LI>
8 <li> content: $ repalce [2] $ </LI>
9 <li> time: $ repalce [3] $ </LI>
10 </body> usage:
1 using system;
2 using system. Data;
3 using system. configuration;
4 using system. Web;
5 using System. Web. Security;
6 using System. Web. UI;
7 using System. Web. UI. WebControls;
8 using System. Web. UI. WebControls. WebParts;
9 using System. Web. UI. HtmlControls;
10
11 namespace UseT
12 {
13 public class Test {
14
15 public void main (){
16 string [] param = new string [4];
17 param [0] = "test template ";
18 param [1] = "nengjiajie ";
19 param [2] = "this is a test article ";
20 param [3] = "2007-10-30 ";
21
22 htmlWeb. CreateHtm cs = new htmlWeb. CreateHtm ();
23 cs. MakeHtml ("Path of the configuration file
24 "," article "," Path of the generated file "," Path of the template file ", param)
25
26}
27}
28}
29. You only need to change the corresponding parameter to the actual value to generate a static file.