第1種方法
用serverExecute(path As Stringwriter As SysetemIOTextWriter) 方法這種方法很簡單向服務器放松動態網頁請求獲取頁面的客戶端html代碼然後把內容寫進文件裡.這種方法寫起來比較簡單
Dim swHtml As StringWriter = New StringWriter()
Server
Execute(
http://localhost/newsSzhome/manage/newstemplate
aspx
swHtml)
Dim strContent As String = swHtml
ToString()
Dim filepath As String =
d//news//
html
If Not (System
IO
Directory
Exists(System
IO
Path
GetDirectoryName(filepath))) Then
System
IO
Directory
CreateDirectory(System
IO
Path
GetDirectoryName(filepath))
End If
Dim sw As StreamWriter = New StreamWriter(filepath
False
System
Text
Encoding
Default)
Try
sw
Write(strContent )
Catch ex As Exception
Throw ex
Finally
sw
Flush()
sw
Close()
End Try
這種方法是必須讀網頁地址缺點顯而易見速度慢另外如果請求的動態頁面有驗證控件的話返回的html頁面卻無法進行數據驗證如果在同一個項目裡的程序用這個還是很好的但是如果是要把生成程序跟網頁程序分開(如寫成webservice)的話用這個方法就相當與去打開一個外網網頁效率肯定會大打折扣(而且我在webservice上用這方法根本運行不了程序出異常!具體原因沒有去探索估計應該是權限的問題).
第2種方法
這個方法跟第1種方法相似(也是需要讀取網頁內容)用SystemNetWebRequestCreate(path As String)方法建裡一個需要讀取的網頁的webRequest再獲得它的WebResponse再以流的形式寫入文件.
SystemNetWebRequest 代碼實例
Dim wReq As System
Net
WebRequest = System
Net
WebRequest
Create(
http://localhost/newsSzhome/manage/newstemplate
aspx
Dim wResp As System
Net
WebResponse = wReq
GetResponse
Dim srs As System
IO
Stream = wResp
GetResponseStream
Dim sr As System
IO
StreamReader = New System
IO
StreamReader(srs
System
Text
Encoding
Default)
GetEncoding(
gb
))
Dim strContent As String = sr
ReadToEnd()
Dim filepath As String =
d://news//
html
If Not (System
IO
Directory
Exists(System
IO
Path
GetDirectoryName(filepath))) Then
System
IO
Directory
CreateDirectory(System
IO
Path
GetDirectoryName(filepath))
End If
Dim sw As StreamWriter = New StreamWriter(filepath
False
System
Text
Encoding
Default)
Try
sw
Write(temp)
Catch ex as Exception
Throw ex
Finally
sw
Flush()
sw
Close()
End Try
效果就不多說了跟第1種方法問題一樣!(但是我在webservice中用上面這個方法生成時還是可以成功的但是速度慢很多.)
第3種
就是最常用也最實用的字符替代方法StringReplace()從文件讀取模版替換模版中的參數後輸出文件這種方法的生成速度上比第一種要快許多而且模版內容可以用工具任意編輯
主要代碼
StringReplace方法
Dim sr As New System
IO
StreamReader(
d://newsDetail_template
htm
System
Text
Encoding
Default)
Dim temp As String = sr
ReadToEnd()
temp = temp
Replace(
@$_CREATEDATE_$@
DateTime
Now
ToString)
Dim filepath As String =
d://news//
html
If Not (System
IO
Directory
Exists(System
IO
Path
GetDirectoryName(filepath))) Then
System
IO
Directory
CreateDirectory(System
IO
Path
GetDirectoryName(filepath))
End If
Dim sw As StreamWriter = New StreamWriter(filepath
False
System
Text
Encoding
Default)
Try
sw
Write(temp)
Catch
Return false
Finally
sw
Flush()
sw
Close()
End Try
這個方法讀取的是硬盤裡的純文件類型在程序後台查詢數據去替換掉模板文件裡的特定字符.
From:http://tw.wingwit.com/Article/program/net/201311/15243.html