实际上,我想读一个文本文件。我使用此代码
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
有效。但不幸的是,当我想阅读一个文本文件(德语,葡萄牙语,瑞典语等)时,它显示了一些奇怪的角色。
原文内容:ÜberQuarantäneÜberprüfen
节目输出:ÃœberQuarantäneÃœberprüfen
我也尝试过Microsoft Rich TextBox Control,但它给了我相同的结果。
我该如何解决这个问题?
答案 0 :(得分:3)
此文件采用UTF-8字符串格式。 VB没有提供读取此类文本的机制。您必须使用API调用将其转换为标准的UTF-16 VB String格式。
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
答案 1 :(得分: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