'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 1:[1]

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).

Solution 2:[2]

I know this is already old, but for future references...
Believe it or not, I had the same problem until I converted my VBS to ANSI (was UTF-8). Then, every new text file created with it was also ANSI and not UTF-8 any more.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ansgar Wiechers
Solution 2 Andrés Puelma