Hi Joergen,
Sometimes, the programmer does not comply with the rules and forgets the
heading of the file.
It is apparement the case as the GetEncoding procedure shows it (b(0) = 34
and b(1) = 73).
However, the detail of UltraEdit editor shows well that it acts of a file to
the format unicode and it seems that in this case, the corresponding heading
is automatically added.
NotePad recognizes automatically a file of the type ANSI, utf-8 or unicode
and never indicates the heading if it is present. With NotePad, You have
also the possibility of saving the file running in a different format.
Here, another method to test if the file is unicode format:
Option Explicit
Private Declare Function IsTextUnicode Lib "advapi32" _
(ByVal lpBuffer As String, ByVal cb As Long, lpi As Long) As Long
' Not need reference to Microsoft Script Runtime with this procedure
Sub Joergen_3()
'// My consts
Const sPath$ = "C:\"
Const sFile$ = "UTF16toDOS.txt"
Const tFile$ = "My_Result_file.txt"
If Not IsUnicode(sPath & sFile) Then Exit Sub
' Convert Unicode to Ascii
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const ModeAscii = 0, ModeUnicode = -1
Dim fso As Object, f_in As Object, f_out As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set f_in = fs
penTextFile(sPath & sFile, ForReading, , ModeUnicode)
Set f_out = fs
penTextFile(sPath & tFile, ForWriting, True, ModeAscii)
Do Until f_in.AtEndOfStream
f_out.Write f_in.Read(1)
Loop
f_in.Close: f_out.Close
Set f_out = Nothing: Set f_in = Nothing: Set fso = Nothing
MsgBox "The unicode file " & sFile & vbLf _
& "was converted into ansi file " & tFile & " !", 64
End Sub
' Returns True if sBuffer evaluates to a Unicode string
Private Function IsUnicode(txtFile As String) As Boolean
Dim Buffer$, f%: f = FreeFile
Open txtFile For Binary Access Read As #f
Buffer = String(LOF(f), Chr(0))
Get #f, , Buffer
Close #f
IsUnicode = IsTextUnicode(ByVal Buffer, Len(Buffer), &HF)
If Not IsUnicode Then MsgBox "It is not a unicode file !", 64
End Function
Regards,
MP