ASP 透過 Scripting.FileSystemObject 可輕鬆讀取、寫入伺服器端文字檔。以下示範以唯讀模式開啟檔案並逐行輸出至網頁。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>讀取文字檔案</title>
</head>
<body>
<%@ LANGUAGE = VBScript %>
<%
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim filename, fs, f, readf, s
filename = "test.txt" ' 相對路徑,預設指向 C:\Winnt 或網站根目錄
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(filename)
Set readf = f.OpenAsTextStream(ForReading, TristateFalse)
' 逐行讀取並輸出
Do While Not readf.AtEndOfStream
s = readf.ReadLine
Response.Write s & "<br>"
Loop
readf.Close
Set readf = Nothing
Set f = Nothing
Set fs = Nothing
%>
</body>
</html>
| 常數 | 值 | 說明 |
|---|---|---|
| ForReading | 1 | 唯讀模式開啟 |
| ForWriting | 2 | 可讀寫模式(覆寫) |
| ForAppending | 8 | 附加模式(寫入檔案末尾) |
| TristateFalse | 0 | ASCII 格式開啟 |
| TristateTrue | -1 | Unicode 格式開啟 |
| TristateUseDefault | -2 | 系統預設格式 |
Set readf = fs.OpenTextFile(filename, ForReading, False, TristateFalse)
注意: 檔案路徑需確保 IUSR / IIS_IUSRS 帳號有讀取權限;生產環境建議使用實體完整路徑或
Server.MapPath避免路徑解析錯誤。