Site Tools


Read and Write UTF-8 Text Files

Developer: RhinoScript
Summary: Demonstrates how to read and write UTF-8 encoded text files using VBScript.

Question

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?

Answer

The File System Object, generally used by VBScript devlopers to read and write text files, can read only ASCII or Unicode text files. You cannot use it to read or write UTF-8 encoded text files.

But, if you can use Microsoft ActiveX Data Objects (ADO), you can read UTF-8 encoded text files like this:

Dim objStream, strData
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\Users\admin\Desktop\test.txt")
strData = objStream.ReadText()

If you want to write a UTF-8 encode text file, you can do so like this:

Dim objStream
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.WriteText "The data I want in utf-8"
objStream.SaveToFile "C:\Users\admin\Desktop\test.txt", 2


developer/scriptsamples/readutf8.txt ยท Last modified: 2020/08/14 (external edit)