How to generate HTML files using ASP. NET

Source: Internet
Author: User

I. (posting)

This function is applicable to websites with poor background database functions, that is, most of the text is not stored in the database records, but in HTML or XML files, and only the index is placed in the database, such as the title, category, and keyword of an article. This method is suitable for websites without database support such as ms SQL Server in the background.

Applicable to news publishing systems, such as Sina and 163, which dynamically generate HTML pages.

Applicable to programs that require dynamic page customization. Such as forums and chat rooms. You can load custom HTML pages to enhance the appearance.

Ideas

1. use a tool such as DW-MX to generate an HTML template, and add special tags (such as $ htmlformat $) where the format needs to be added. When a file is dynamically generated, use the code to read the template, obtain the content entered at the front end, add it to the tag location of this template, generate a new file name, and write it to the disk. Then, write the data to the database.

2. html files are hardcoded Using Background code. You can use the htmltextwriter class to write HTML files.

Advantages

1. you can create complex pages and add document to the JS file by using methods that contain JS files. the write () method can be used to add content such as the page header and advertisement to all pages.

2. The Index Server of Ms Windows2000 can be used to create a full-text search engine for static html files, and Asp.net can be used to obtain search results in datatable mode. The Index Service of Win2000 cannot find the content of XML files. If both database search and index search are included, this search function is very powerful.

3. Saving server load and saving a lot of resources by requesting a static html file than An ASPX file server.

Disadvantages

Train of Thought 2: If hard encoding is used, the workload is very heavy and a lot of HTML code is required. Debugging is difficult. In addition, HTML styles generated by hard encoding cannot be modified. If the style of a website is changed, it must be re-encoded, which brings a huge workload in the future.

Therefore, the first approach is adopted here.

Column code

1.define (template.htm) HTML template page

 

<HTML>

<Head>

<Title> </title>

<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">

</Head>

<Body>

<Table $ htmlformat [0] Height = "100%" border = "0" width = "100%" cellpadding = "10" cellspacing = "0" bgcolor = "# eeeeee" style = "Border: 1px solid #000000 ">

<Tr>

<TD width = "100%" valign = "Middle" align = "Left">

<Span style = "color: $ htmlformat [1]; font-size: $ htmlformat [2]"> $ htmlformat [3] </span>

</TD>

</Tr>

</Table>

</Body>

</Html>

2.asp.net code:

// --------------------- Read the HTML template page to the stringbuilder object ----

String [] format = new string [4]; // defines an array with the same number of htmlyem tags

Stringbuilder htmltext = new stringbuilder ();

Try

{

Using (streamreader sr = new streamreader ("path for storing template pages and Page name "))

{

String line;

While (line = Sr. Readline ())! = NULL)

{

Htmltext. append (line );

}

Sr. Close ();

}

}

Catch

{

Response. Write ("<SCRIPT> alert ('file reading error') </SCRIPT> ");

}

// --------------------- Assign a value to the tag array ------------

Format [0] = "background =/" bg.jpg/"; // background image

Format [1] = "#990099"; // font color

Format [2] = "150px"; // font size

Format [3] = "<marquee> generated template HTML page </marquee>"; // text description

// ---------- Replace the content marked in HTM with the content you want to add

For (INT I = 0; I <4; I ++)

{

Htmltext. Replace ("$ htmlformat [" + I + "]", format [I]);

}

// ---------- Generate the HTM file ------------------――

Try

{

Using (streamwriter Sw = new streamwriter ("Storage path and Page name", false, system. Text. encoding. getencoding ("gb2312 ")))

{

Sw. writeline (htmltext );

Sw. Flush ();

Sw. Close ();

}

}

Catch

{

Response. Write ("the file cocould not be wirte :");

}

Summary

This method can be used to easily generate HTML files. The program uses cyclic replacement, so it is very fast for templates that need to replace a large number of elements.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

2. My instances:

Void turnhtml ()
{

String htmltext = "";

Try

{

Using (streamreader sr = new streamreader ("F: // OA // html // a.txt "))

{

String line;

// Use while to read all the content in the template in one row
While (line = Sr. Readline ())! = NULL)

{

Htmltext + = line;

}
Hlink. value = htmltext; // HLINK is a hidden input, which can also be a string.

Sr. Close ();

}

}

Catch

{

Response. Write ("<SCRIPT> alert ('file reading error') </SCRIPT> ");

}

Sqlconnection conn;
Conn = new sqlconnection (configurationsettings. receivettings ["cnstr"]);
Conn. open ();
Sqlcommand CM = new sqlcommand ("select top 5 WID, title, neirong from tweb order by wid desc", Conn );
Sqldatareader DR = cm. executereader ();
While (dr. Read ())
{
Htmltext = hlink. value;

// --------------------- Assign a value to the tag array ------------
String [] format = new string [2];
Format [0] = Dr ["title"]. tostring ();
Format [1] = Dr ["neirong"]. tostring ();
For (INT I = 0; I <2; I ++) // write a few numbers if there are several variables.
{
Htmltext = htmltext. Replace ("$ htmlformat [" + I + "]", format [I]);

// ---------- Replace the content marked in HTM with the content you want to add
}

Using (streamwriter Sw = new streamwriter ("F: // OA // html //" + Dr ["wid"]. tostring () + ". html ", false, system. text. encoding. getencoding ("gb2312 ")))

{

Sw. writeline (htmltext );

Sw. Flush ();

Sw. Close ();
}
}
Dr. Close ();
Conn. Close ();
Label2.text = "HTML generated successfully! ";
// The ASPX page also contains validaterequest = false to prevent errors during the second click.

}

 

 

 

 

 

 

 

 

 

 

 

3. Reprinted:

<! -- Main. aspx -->
<% @ Page Language = "C #" %>
<% @ Import namespace = system. Io %>
<SCRIPT runat = "server">
Protected override void oninit (eventargs E)
{
Int ID;
Try
{
Id = int. parse (request. querystring ["ID"]);
}
Catch
{
Throw (new exception ("No ID specified on the page "));
}
 
String filename = server. mappath ("statichtml _" + ID + ". html ");
 
// Try to read an existing file
Stream S = getfilestream (filename );
If (s! = NULL) // if the file exists and is read successfully
{
Using (s)
{
Stream2stream (S, response. outputstream );
Response. End ();
}
}
 
 
// Call main_execute and obtain its output
Stringwriter Sw = new stringwriter ();
Server. Execute ("main_execute.aspx", SW );
 
String content = Sw. tostring ();
 
// Output to the client
Response. Write (content );
Response. Flush ();
 
// Write the file
 
Try
{
Using (filestream FS = new filestream (filename, filemode. Create, fileaccess. Write, fileshare. Write ))
{
Using (streamwriter = new streamwriter (FS, response. contentencoding ))
{
Streamwriter. Write (content );
}
}
}
Finally
{
// Response. End ();
}
}
Static public void stream2stream (Stream SRC, stream DST)
{
Byte [] Buf = new byte [1, 4096];
While (true)
{
Int c = SRC. Read (BUF, 0, Buf. Length );
If (C = 0)
Return;
DST. Write (BUF, 0, C );
}
}
Public stream getfilestream (string filename)
{
Try
{
Datetime dt = file. getlastwritetime (filename );
Timespan Ts = DT-datetime. now;
If (TS. totalhours> 1)
Return NULL; // expired after 1 hour
Return new filestream (filename, filemode. Open, fileaccess. Read, fileshare. Read );
}
Catch
{
Return NULL;
}
}
</SCRIPT>

<! -- Main_execute.aspx -->
<% @ Page Language = "C #" %>
<HTML>
<Head runat = "server">
<Title> untitled page </title>
</Head>
<Body>

ID:
<% = Request. querystring ["ID"] %>

</Body>
</Html>

 

The principle is as follows.
Main_execute.aspx is the HTML page generated.

Now we use main. aspx to cache it.
The process is as follows:

First, calculate the file name based on the page parameters. (This example is based on request. querystring ["ID)
Try to read the cached file. If successful, then response. End ();
If not:
Use server. Execute to call main_execute.aspx and obtain its results.
After the content is obtained, it is immediately output to the client.
Finally, write the content into the file and provide it to the next cache.

 

 

Finally, I don't know whether the first method is good or the third method is good. The first thing is better understanding.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.