雖然 ASP.NET 已取代傳統 ASP,但在維護舊系統時仍常需使用 Scripting.FileSystemObject (FSO) 進行文字檔讀寫。本文詳細說明 FSO 核心屬性、方法與參數,並提供「讀檔」、「寫檔」與「簡易訪客計數器」三個完整實作範例。
| 成員 | 說明 |
|---|---|
AtEndOfStream | Boolean,指標是否已到達檔案末尾 |
CreateTextFile(filename[, overwrite[, unicode]]) | 建立新文字檔,傳回 TextStream 物件 |
OpenTextFile(filename, iomode[, create[, format]]) | 開啟既有檔案,傳回 TextStream |
1 = ForReading:唯讀 (預設)2 = ForWriting:覆寫模式,開啟後指標在檔案開頭8 = ForAppending:附加模式,指標在檔案結尾create 參數為 True 時,檔案不存在會自動建立;False 則拋出錯誤。
<%
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(Server.MapPath("data.txt"), 1) ' ForReading
Do While Not ts.AtEndOfStream
Response.Write ts.ReadLine & "
"
Loop
ts.Close
Set ts = Nothing
Set fso = Nothing
%>
<%
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set ts = fso.CreateTextFile(Server.MapPath("log.txt"), True) ' 覆寫
ts.WriteLine "第一行記錄:" & Now()
ts.WriteLine "第二行記錄:使用者登入"
ts.Close
Set ts = Nothing
Set fso = Nothing
%>
<%
Dim fso, filePath, ts, counter
Set fso = Server.CreateObject("Scripting.FileSystemObject")
filePath = Server.MapPath("counter.txt")
' 讀取現有計數
Set ts = fso.OpenTextFile(filePath, 1, True) ' ForReading, 不存在則建立
counter = 0
If Not ts.AtEndOfStream Then counter = CLng(ts.ReadLine)
ts.Close
' 遞增並寫回
counter = counter + 1
Set ts = fso.OpenTextFile(filePath, 2, True) ' ForWriting
ts.Write counter
ts.Close
Response.Write "您是第 " & counter & " 位訪客! "
Set ts = Nothing
Set fso = Nothing
%>
counter.asp (輸出 JavaScript):
<%
Response.Write "document.write('您是第 " & counter & " 位訪客!');"
%>
index.html:
<script src="counter.asp"></script>
Server.MapPath 轉換為實體路徑,勿硬編碼絕對路徑。