萬盛學電腦網

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

ASP 讀取文字檔並逐行顯示內容

使用 FileSystemObject 讀取文字檔案

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>

參數說明

常數值說明
ForReading1唯讀模式開啟
ForWriting2可讀寫模式(覆寫)
ForAppending8附加模式(寫入檔案末尾)
TristateFalse0ASCII 格式開啟
TristateTrue-1Unicode 格式開啟
TristateUseDefault-2系統預設格式

替代寫法:OpenTextFile

Set readf = fs.OpenTextFile(filename, ForReading, False, TristateFalse)

注意: 檔案路徑需確保 IUSR / IIS_IUSRS 帳號有讀取權限;生產環境建議使用實體完整路徑或 Server.MapPath 避免路徑解析錯誤。

copyright © 萬盛學電腦網 all rights reserved