2

I have the following code to read a text file:

Option Explicit 
Dim InputFile 
Dim FSO, oFile 
Dim strData 

InputFile = "C:\Program Files (x86)\AVG\CloudCare\ClientVersion.txt" 
Set FSO = CreateObject("Scripting.FileSystemObject") 
Set oFile = FSO.OpenTextFile(InputFile) 
strData = oFile.ReadAll 
oFile.Close 
msgbox strData 

The contents of ClientVersion.txt is:

CLIENT_VERSION_STRING   _T("3.5.2") //

When I run the VBS code, I get back this:

VBS txt file read

If I create a new text file with the same content in the same location, it works fine. Is there a reason why VBS is unable to read this simple text file? I couldn't see any issues with permissions on the file.

user692942
  • 16,398
  • 7
  • 76
  • 175
user2924019
  • 1,983
  • 4
  • 29
  • 49

1 Answers1

6

ÿþ is the byte order mark of a UTF-16 Little Endian encoded file. UTF-16 (unlike ASCII/ANSI) uses two bytes for a character instead of just one. However, the OpenTextFile method reads files as ASCII files by default, so each 2-byte character gets interpreted as two separate characters.

From the documentation:

Syntax

object.OpenTextFile(filename[, iomode[, create[, format]]])

Arguments
[…]
format
    Optional. One of three Tristate values used to indicate the format of the opened file (TristateTrue = -1 to open the file as Unicode, TristateFalse = 0 to open the file as ASCII, TristateUseDefault = -2 to open the file as the system default). If omitted, the file is opened as ASCII.

Specify the proper encoding when reading the file and the problem will disappear:

Set oFile = FSO.OpenTextFile(InputFile, 1, False, -1)
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328