萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP FSO (FileSystemObject) 讀寫文字檔完整教學與計數器實作

ASP 經典檔案操作:Scripting.FileSystemObject 完整指南

雖然 ASP.NET 已取代傳統 ASP,但在維護舊系統時仍常需使用 Scripting.FileSystemObject (FSO) 進行文字檔讀寫。本文詳細說明 FSO 核心屬性、方法與參數,並提供「讀檔」、「寫檔」與「簡易訪客計數器」三個完整實作範例。

常用屬性與方法速查表

成員說明
AtEndOfStreamBoolean,指標是否已到達檔案末尾
CreateTextFile(filename[, overwrite[, unicode]])建立新文字檔,傳回 TextStream 物件
OpenTextFile(filename, iomode[, create[, format]])開啟既有檔案,傳回 TextStream

OpenTextFile 的 iomode 參數

  • 1 = ForReading:唯讀 (預設)
  • 2 = ForWriting:覆寫模式,開啟後指標在檔案開頭
  • 8 = ForAppending:附加模式,指標在檔案結尾

create 參數為 True 時,檔案不存在會自動建立;False 則拋出錯誤。

範例 1:逐行讀取文字檔

<%
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 %>

範例 2:建立新檔並寫入內容

<%
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
%>

範例 3:最簡單的文字檔訪客計數器

<%
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 %>

在靜態 HTML 頁面引用計數器

counter.asp (輸出 JavaScript):

<%
Response.Write "document.write('您是第 " & counter & " 位訪客!');"
%>

index.html:

<script src="counter.asp"></script>

效能與安全提醒

  • 高流量網站請改用資料庫或 Application 變數計數,避免檔案 I/O 瓶頸與競爭條件。
  • 檔案路徑請使用 Server.MapPath 轉換為實體路徑,勿硬編碼絕對路徑。
  • 寫入前請檢查資料夾寫入權限 (IUSR/IIS_IUSRS 需具備修改權限)。
copyright © 萬盛學電腦網 all rights reserved