2017-05-03 59 views
3

其實,我想讀取一個文本文件。我使用此代碼VB6用Deutsch字符讀取文件

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

我已經試過微軟格式文本框控件太多,但它給了我同樣的結果。

我該如何解決這個問題?

回答

3

此文件採用UTF-8字符串格式。 VB不提供讀取這種文本的機制。您將不得不使用API​​調用將其轉換爲標準的UTF-16 VB字符串格式。

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