Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

utf 8 - Read utf-8 text file in vbscript

I have a text file saved as UTF-8 and when I try to read the file it gives me weird characters and not the correct characters (it contains Chinese characters). How can I make it give me the correct Chinese characters?

Option Explicit

Dim objFSO, strTextFile, strData, strLine, arrLines, aniTextFile, aniData, aniLines, aniLine, objTextFile, fso, inputFileList, listFile, fname
Dim iim1, iret, iret2, iret3, i
Const ForReading   = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
strTextFile = "C:UsersadminDesktopArtistCGfolder.txt"
strData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll
arrLines = Split(strData,vbCrLf)

aniTextFile = "C:UsersadminDesktopArtistCGfolder-list.txt"
aniData = objFSO.OpenTextFile(aniTextFile,ForReading).ReadAll
aniLines = Split(aniData,vbCrLf)

For i = 0 To UBound(arrLines)
  strData = objFSO.OpenTextFile(arrLines(i),ForReading).ReadAll
  WScript.Echo strData

  Set listFile = objFSO.OpenTextFile(aniLines(i),ForReading)
  Do While Not listFile.AtEndOfStream
    fName = listFile.ReadLine
    WScript.Echo fName
  Loop
  listFile.Close
Next 
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the documentation:

The FSO can read only ASCII text files. You cannot use the FSO to read Unicode files or to read binary file formats such as Microsoft Word or Microsoft Excel.

Since you got weird characters, I guess that's somewhat incorrect and the file was read in some 8-bit windows code page because if it really could read only ASCII, you would have seen ????

Anyway, if you can use ADO, you can do this:

Dim objStream, strData

Set objStream = CreateObject("ADODB.Stream")

objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:UsersadminDesktopArtistCGfolder.txt")

strData = objStream.ReadText()

objStream.Close
Set objStream = Nothing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...