回复人: TomMax(笑望人生) ( ) 信誉:100
首先定义一个html的模板文件,这个文件用什么软件写都可以,假设如下:
<html>
<head>
<title>模板文件</title>
</head>
<body>
A1a1A1a1A1a1
</body>
</html>
这个“A1a1A1a1A1a1”就是替换关键字。
假设保存在网站根目录下的text目录里面,名称是templates.htm
然后定义一个类,用System.IO.StreamReader读取,System.IO.StreamWriter写,然后把信息写入数据库。代码如下(vb)
Imports System.Web
Imports System.IO
Imports System.Text
Imports System.Data.OleDb
Public Class WriteFileClass
Private myConn As OleDbConnection
'构造函数
Public Sub New()
myConn = New OleDbConnection("数据库连接字符串")
End Sub
'公共方法,写文件
Public Function WriteHtmlFile (ByVal Detail As String) As Boolean
'首先调用GetRandom()方法生成文件名
Dim FileName As String = GetRandom() & ".html"
'然后把输入的写入内容和文件名作为参数调用WriteFile()方法,写文件,写入
'成功后写入数据库
If Not WriteFile(Detail,FileName) Then
Return False
End If
If (WriteFile(FileName)) Then
Return True
Else
Return False
End If
End Function
' - - - - - - - - - - - - - - - - - - - - -
' 生成随机文件名
Private Function GetRandom() As String
Dim objRandom As System.Random
Dim intNumber As Integer
Dim intDateNum As Long
Dim strNumber As String
Dim dat_DateTime As DateTime
strNumber = dat_DateTime.Now.ToString
strNumber = strNumber.Replace(":", "")
strNumber = strNumber.Replace("-", "")
strNumber = strNumber.Replace(" ", "")
intDateNum = CType(strNumber, Long)
objRandom = New Random(Int((1 + 10 - 1) * CType(Rnd(), Integer)))
intNumber = objRandom.Next(10000, 99999)
objRandom = Nothing
Return (intDateNum + intNumber).ToString()
End Function
'写入文件
Private WriteFile(strDetail As String,strName As String) As Boolean
'设定写入路径,网站根目录下的text目录
Dim Path As String = HttpContext.Current.Server.MapPath("../text/")
'设定编码,设定好了才能写中文
Dim code As Encoding = Encoding.GetEncoding("gb2312")
'读取模板文件
Dim tmpFile As String = HttpContext.Current.Server.MapPath("../text/templates.htm")
Dim sr As StreamReader, sw As StreamWriter, str As String
Try
sr = New StreamReader(tmpFile, code)
str = sr.ReadToEnd()
Catch ex As Exception
Throw New ApplicationException("读取模板文件错误:" & ex.Message, ex)
Return False
Finally
sr.Close()
End Try
'这时候,str字符串中的内容就是模板文件内容,然后用
'Replace方法替换字符串即可
str = str.Replace("A1a1A1a1A1a1", strDetail)
'写文件
Try
sw = New StreamWriter(Path & strName, False, code)
sw.Write(str)
sw.Flush()
Catch ex As Exception
Throw New Exception("文件写入失败:" & ex.Message, ex)
Return False
Finally
sw.Close()
End Try
Return True
End Function
'把文件信息写入数据库
Private Function WirteDb( strFileName As String) As Boolean
'strFileName是文件名,写入数据库即可
'代码简单,我就不写了。
End Function
//---------------------------
使用可以用这个类
Dim write As New WriteFileClass()
write.WriteHtmlFile("你好")