在ASP中读取文本文件的方法。一种是用FileSystemObject,一种是用ADODB.Stream。
' 读取文本文件
Function ReadTextFile(sFilePath)
Dim oFS, oFile, sFileContent
Set oFS = Server.CreateObject("Scripting.FileSystemObject")
' 1 - ForReading
' -2 - TristateUseDefault 使用系统默认的格式打开文件
Set oFile = oFS.OpenTextFile(sFilePath, 1, False, -2)
sFileContent = oFile.ReadAll
Set oFile = Nothing
Set oFS = Nothing
ReadTextFile = sFileContent
End Function
' 读取指定编码格式的文本文件
Function ReadEncodedTextFile(sFilePath, sCharset)
Dim oStream, s
s = ""
Set oStream = Server.CreateObject("ADODB.Stream")
' 以文本模式读取
oStream.Type = 2
oStream.Mode = 3
If Len(sCharset) > 0 Then
On Error Resume Next
oStream.Charset = sCharset
If Err.number <> 0 Then
oStream.Charset = "_autodetect_all"
's = s & "指定的编码 " & sCharset & " 未得到 ReadEncodedTextFile() 函数的支持,已自动以 " & oStream.Charset & " 编码格式读取文件。" & vbCrLf & vbCrLf
s = s & "The specified charset (" & sCharset & ") is not supported by Function ReadEncodedTextFile(), the charset specified is automatically changed to (" & oStream.Charset & ")." & vbCrLf & vbCrLf
End If
On Error Goto 0
End If
oStream.Open
oStream.LoadFromFile sFilePath
s = s & oStream.ReadText
oStream.Close
Set oStream = Nothing
ReadEncodedTextFile = s
End Function