2017-05-03 3 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

프로그램 출력 : Ãœber Quarantäne Ãœberprüfen

나도 Microsoft 서식있는 텍스트 상자 컨트롤을 시도했다, 그러나 그것은 나에게 같은 결과를 제공합니다.

이 문제는 어떻게 해결할 수 있습니까?

답변

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