How to change the encoding format of a text file from Unicode to UTF-8

Dim txtFile, fileObj, streamObj, s

Set txtFile = CreateObject(fileName)

Set streamObj = CreatreObject("adodb.Stream")
streamObj.Charset = "UTF-8"
streamObj.open
Set fileObj = txtFile.OpenTextFile("filePath")

Do Until fileObj.AtEndOfStream
      s = fileObj.ReadLine
      txtObj.WriteText s
Loop

txtObj.SaveToFile "D:\A4\Message_tool\surya.msg", 2
fileObj.Close

      

After executing this code, the encoding format of surya.msg is "ANSCII", but I want it to be "UTF-8"

+3


source to share


2 answers


Const adTypeText = 2
Const adSaveCreateOverWrite = 2

Dim inputFile, outputFile
    inputFile = "input_file.txt"
    outputFile = "output_file.txt"

Dim inputStream
    Set inputStream  = WScript.CreateObject("adodb.stream")
    With inputStream
        .Type = adTypeText
        .Charset = "unicode"
        .Open
        .LoadFromFile inputFile
    End With

Dim outputStream
    Set outputStream = WScript.CreateObject("adodb.stream")
    With outputStream
        .Type = adTypeText
        .Charset = "utf-8"
        .Open
        .WriteText inputStream.ReadText
        .SaveToFile outputFile, adSaveCreateOverWrite
    End With

    inputStream.Close
    outputStream.Close

      



+2


source


Unicode text files can be opened in the usual way using the OpenTextFile()

class method FileSystemObject

. Just pass True

/ -1

for the 4th ("format") parameter.

strText = objFSO.OpenTextFile(inputFile, , , True).ReadAll()

      

To encode text as UTF-8 you need to use the class ADO Stream

.



Const adTypeText = 2
Const adSaveCreateOverWrite = 2

With CreateObject("ADODB.Stream")
    .Type = adTypeText
    .Charset = "utf-8"
    .Open
    .WriteText strText
    .SaveToFile "D:\A4\Message_tool\surya.msg", adSaveCreateOverWrite 
End With

      

A list of character encodings supported by Windows can be found in the following registry key:

HKEY_CLASSES_ROOT\MIME\Database\Charset

      

0


source







All Articles