VB6 read file with Deutsch character

Actually, I want to read a text file. And I am using this code

Function FileText(filename$) As String
    Dim handle As Integer
    handle = FreeFile
    Open filename$ For Input As #handle
    FileText = Input$(LOF(handle), handle)
    FileText = StrConv(StrConv(FileText, vbUnicode), vbFromUnicode)
    Close #handle
End Function

      

It works. But unfortunately, when I want to read a text file (in Deutsch, Portuguese, Swedish, etc.), It shows some strange character.

Original text content: Über Quarantäne Überprüfen

Program exit: Ãœber Quarant¤¤ Ãœberprüfen

I tried Microsoft Rich TextBox Control too, but it gives me the same result.

How can I fix this problem?

+3


source to share


2 answers


This file is in UTF-8 string format. VB does not provide a mechanism for reading such text. You will need to use an API call to convert it to the standard VB String-UTF-16 string format.



Private Declare Function MultiByteToWideChar Lib "Kernel32.dll" ( _
    ByVal CodePage As Long, _
    ByVal dwFlags As Long, _
    ByRef lpMultiByteStr As Byte, _
    ByVal cbMultiByte As Long, _
    ByVal lpWideCharStr As Long, _
    ByVal cchWideChar As Long _
) As Long

' "Code Page" for UTF8.
Private Const CP_UTF8 As Long = 65001

Function ReadAllFromUtf8TextFile(ByRef the_sFileName As String) As String

    Dim nFileNo     As Long
    Dim abytData()  As Byte
    Dim nDataLen    As Long
    Dim nStringLen  As Long

    ' Get the next available file no.
    nFileNo = FreeFile

    ' Open the file as binary data, resize a Byte array to fit, copy the file contents into the Byte array, and close the file.
    Open the_sFileName For Binary As #nFileNo
    nDataLen = LOF(nFileNo)
    ReDim abytData(1 To nDataLen)
    Get #nFileNo, , abytData()
    Close #nFileNo

    ' Work out the size in characters that the data will be when converted.
    nStringLen = MultiByteToWideChar(CP_UTF8, 0&, abytData(1), nDataLen, 0&, 0&)

    ' Allocate an output string buffer for this number of characters.
    ReadAllFromUtf8TextFile = Space$(nStringLen)

    ' Actually do the conversion of the data in the Byte array to the output string buffer.
    MultiByteToWideChar CP_UTF8, 0&, abytData(1), nDataLen, StrPtr(ReadAllFromUtf8TextFile), nStringLen

End Function

Private Sub Command_Click()

    MsgBox ReadAllFromUtf8TextFile("C:\Document1.txt")

End Sub

      

+3


source


You can use ADO as a helper library for this kind of thing:



Dim Text As String

With New ADODB.Stream
    .Type = adTypeText
    .Charset = "utf-8"
    .Open
    .LoadFromFile "utf8.txt"
    Text = .ReadText(adReadAll)
    .Close
End With

      

0


source







All Articles