Need to convert text files to Unicode from UTF8 in vbscript

42,393

Unfortunately VBScript doesn't support this kind of conversion by itself. You can use an ADODB.Stream object, though:

Set stream = CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2 'text
stream.Charset = "utf-8"
stream.LoadFromFile "C:\input.txt"
text = stream.ReadText
stream.Close

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("C:\output.txt", 2, True, True)
f.Write text
f.Close

Or a little more streamlined:

Set fso = CreateObject("Scripting.FileSystemObject")

Set stream = CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2 'text
stream.Charset = "utf-8"
stream.LoadFromFile "C:\input.txt"
fso.OpenTextFile("C:\output.txt", 2, True, True).Write stream.ReadText
stream.Close

If you want to replace the existing file you'll have to use the first version and use the same file for input and output. Use a loop like this to iterate over all files in a folder:

Set fso = CreateObject("Scripting.FileSystemObject")
Set stream = CreateObject("ADODB.Stream")

For Each f In fso.GetFolder("C:\source\folder").Files
  stream.Open
  stream.Type = 2 'text
  stream.Charset = "utf-8"
  stream.LoadFromFile f.Path
  text = stream.ReadText
  stream.Close

  fso.OpenTextFile(f.Path, 2, True, True).Write text
Next
Share:
42,393
user1723699
Author by

user1723699

Updated on December 01, 2020

Comments

  • user1723699
    user1723699 over 3 years

    I have a bunch of text files in a folder that I need to change the encoding on to Unicode and instead of manually opening the files and saving them as Unicode I would like to have a script to do this.

    The files are currently in UTF-8 encoding and my extremely limited scripting abilities can't figure this one out. I found the code below to convert to Unicode from ANSI and when I use this code it does convert it to Unicode but it messes up the characters so the conversion doesn't actually work. Any thoughts? Thanks in advance.

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set oFolder = fso.GetFolder("C:\test")
    Set oFiles = oFolder.files
    
    For each file in oFiles
    If Right(file.Name, 3) = "txt" Then
    Set ANSIFile = fso.OpenTextFile(file.path, 1, False, False)
    ANSIContent = ANSIFile.ReadAll
    Set UNICODEFile = fso.OpenTextFile(file.path, 2, False, True)
    UNICODEFile.Write ANSIContent
    End If
    Next