如何以正确的编码格式来读取文件呢?很简单,使用ADODB.Stream对象来读取文件,并给它的Charset属性赋值为_autodetect_all。
如下面的函数将以指定的编码格式来读取文本文件,并将文本内容作为字符串返回。
' 读取指定编码格式的文本文件
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
要以正确的编码格式来读取文本文件,只需要这样调用。
Dim s
s = ReadEncodedTextFile("file.txt", "_autodetect_all")