Tuesday, May 5, 2009

Determing a File Encoding in VB

Ever have to open a file in VBS and its all messed up. The file may be in UTF8 or Unicode.
The is especially annoying for SQL files so I did this:

'**************************************************
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("C:\UnknownFile.SQL")
'Set this to false so it opens as ascii
Set objTextStream = objFile.OpenAsTextStream(1,False)
'Grab the first line

strTemp = objTextStream.ReadLine

If InStr(strTemp,"") > 0 Then
'UTF8 = depends on the content
'I stripped out the wacky characters and was OK

MsgBox("File is UTF8")
ElseIf InStr(strTemp,"ÿþ/") > 0 Then
'Unicode = just open the file again with
'Set objTextStream = objFile.OpenAsTextStream(1,True)

MsgBox("File is Unicode")
Else
'File is normal
MsgBox("File is ANSI")
End If

'**************************************************

No comments:

Post a Comment