Lou
Lou

Reputation: 403

vbscript prevent text conversion during reading from text file

I'm having an issue when reading text from a text file. Here's the code that creates the text file if it doesn't exist, then enters the text in the file:

Dim fso, strUser, strUserInit, strUserData, strNewFile
Dim strGetUser, strNextUser, strInit
Const ForReading = 1, ForWriting = 2, ForAppending = 8

' %user% contains USERPROFILE (C:\Users\username) gathered earlier from Macro Express
strUser = "%user%"
strUserInit = strUser & "\Documents\UserInitFile.txt"

If fso.FileExists(strUserInit) Then
' Do nothing
Else
    strUserData = UCase(InputBox("Please enter your first and last initials (ex. John Doe = JD)", "Enter Initials"))
    Set strNewFile = fso.CreateTextFile(strUserInit, ForWriting, True)
    strNewFile.WriteLine(strUserData)
    strNewFile.Close
End If

Set strGetUser = fso.OpenTextFile(strUserInit, ForReading)
Do Until strGetUser.AtEndOfStream
   strNextUser = strGetUser.ReadAll
Loop

strInit = Left(strNextUser, 2)

What is happening is, when prompted for first and last initials, I enter the initials "LP". However, when I read from the file, they end up being "ÿþ". I looked in the file that was created and it shows "LP". How do I prevent text from being converted when reading from the file? I've used the same exact code for other reasons and never had the text converted when reading from the file.

Upvotes: 0

Views: 199

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38755

Use the docs to see why

fso.CreateTextFile(strUserInit, ForWriting, True)

creates an UTF-16 encoded file. See this to understand why I fear there is a virus going around that makes people mixup .OpenTextFile and .CreateTextFile.

Upvotes: 1

Related Questions