2017-05-03 14 views
3

実際には、テキストファイルを読んでいます。私はこのコードを使用します。VB6ドイツ語文字でファイルを読む

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 

これは機能します。しかし残念ながら、テキストファイル(ドイツ語、ポルトガル語、スウェーデン語など)を読みたいと思ったら、それは奇妙な文字を表示します。

オリジナルテキストコンテンツ:ユーバーQuarantäneÜberprüfen

プログラム出力:ÃœberQuarantäneÃœberprüfen

私もMicrosoftリッチテキストボックス(TextBox)コントロールを試してみましたが、それは私に同じ結果を与えます。

この問題を解決するにはどうすればよいですか?

答えて

3

このファイルは、UTF-8文字列形式です。 VBでは、この種のテキストを読み取るメカニズムは提供していません。これを標準のUTF-16 VB String形式に変換するには、API呼び出しを使用する必要があります。

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 
0

あなたはこの種のもののためのヘルパーライブラリとしてADOを使用することができます。

Dim Text As String 

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