Search code examples
utf-8vbscriptansi

Create ANSI text file using vbscript


I must create a text file with ANSI encoding using vbs.

If I just create it, without to write any text, using this code...

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ObjFileTxt = objFSO.objFSO.CreateTextFile("filename.txt", True, False)  
Set ObjFileTxt = nothing
Set objFSO = nothing

... I get an ANSI text file, but if I try to write some text, for example...

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ObjFileTxt = objFSO.CreateTextFile("filename.txt", True, False)   
ObjFileTxt.Write "ok"
Set ObjFileTxt = nothing
Set objFSO = nothing

... I get an UTF8 text file.

Any help?


Solution

  • It's not possible that the code you posted would create a UTF8-encoded output file. The CreateTextFile method supports only ANSI (windows-1252) and Unicode (little endian UTF-16) encodings.

    The only ways to create UTF8-encoded files in VBScript are the ADODB.Stream object:

    Set stream = CreateObject("ADODB.Stream")
    stream.Open
    stream.Type     = 2 'text
    stream.Position = 0
    stream.Charset  = "utf-8"
    stream.WriteText "some text"
    stream.SaveToFile "C:\path\to\your.txt", 2
    stream.Close
    

    or writing the individual bytes (including the BOM).