Gennaro Lippiello
Gennaro Lippiello

Reputation: 73

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?

Upvotes: 2

Views: 9395

Answers (2)

Andrés Puelma
Andrés Puelma

Reputation: 1

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.

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

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

Upvotes: 4

Related Questions