Hi David,
 
I didn't think you could use createTextFile to read from a file, but then, I
don't have the docs handy, so maybe it's possible.
 
Below is an example I use to look at the first byte, and then open the file
properly:
 
Set oFS = CreateObject("scripting.FileSystemObject")
loadClassInformation oFS
 
If Not oFS.FileExists(strFileName) Then
MsgBox "Could not find file: " & strFileName
Exit Sub
End If
 
Set oText = Nothing
On Error Resume Next
Set oText = oFS.OpenTextFile(strFileName, ForReading, False) ' ascii
If oText Is Nothing Then
MsgBox "Error " & Err.Description & " when opening file " & strFileName
On Error GoTo 0
Exit Sub
End If
' see if this is a unicode file, and reopen it if it is
Dim char As String
char = oText.Read(1)
If Asc(char) = 255 Then
' it's likely to be unicode
oText.Close
Set oText = oFS.OpenTextFile(strFileName, ForReading, False, TristateTrue) '
unicode
If oText Is Nothing Then
MsgBox "Error " & Err.Description & " when opening file " & strFileName
On Error GoTo 0
Exit Sub
End If
On Error GoTo 0
 
Else
' not Unicode, so it is likely to be ascii; go back to beginning
oText.Close
Set oText = oFS.OpenTextFile(strFileName, ForReading, False) ' ascii
End If
On Error GoTo 0
 
 
 


  _____  

From: David [mailto:[email protected]] 
Sent: Thursday, October 27, 2011 10:36 PM
To: [email protected]
Subject: How to detect textfile format?


In my script, I want to read the information from a text file. 
 
As it is going to read from any text file on the disk, I have no clue
whether the actual text file will be an ASCII, or an Unicode file. I am
using the CreateTextFile method to open the text file. This method does
require me to determine if I am going to open one or the other of the file
formats. Is there any good work around for this in VBS? Some way for me to
open a text file, and have it properly read, no matter which of the two
formats it has been saved in?
 
>From my testing here, I get the following results. Try to open an ASCII
file, having CreateTextFile set to UniCode, only gives me one line, and no
recognized text. 
 
Try to open an UniCode file, having CreateTextFile set to ASCII, will
recognize all the lines, but does not work properly when I try to perform
textual operations; like Mid, and InStr.
 
Yep, even computers have their multi-lingual challenges. Smile.
 
Anyone has a good idea here, I would be thankful.
 
 

Reply via email to