在 VB6 中追加写入文本文件(utf-8 编码) [英] Write text file in appending (utf-8 encoded) in VB6
问题描述
我必须在 VB6 中编写一个文本文件.我需要在附加和 utf-8 编码中做到这一点.
I have to write a textfile in VB6. I need to do it in appending and utf-8 encoded.
我尝试了两种解决方案,一种使用TextStream",另一种使用ADODB.Stream".
I tried two solutions, one with "TextStream" and another one with "ADODB.Stream".
第一个:
Set fsoFile = fso.OpenTextFile(FileIn(fi), ForAppending, True)
fsoFile.WriteLine "<tag>kkkjòòkkkkjlòlk</tag>"
fsoFile.Close
在附加方面效果很好,但我怎样才能把它写成 utf-8 编码?
Works good in appending but how can I write it utf-8 encoded?
第二个:
Dim ST As ADODB.Stream
Set ST = New ADODB.Stream
ST.Mode = adModeReadWrite
ST.Type = adTypeText
ST.Charset = "UTF-8"
ST.Open
ST.LoadFromFile FileIn(fi)
ST.Position = ST.Size
ST.WriteText "<tag>kkkjòòkkkkjlòlk</tag>"
ST.SaveToFile FileIn(fi)
ST.Close
在 utf-8 中正确写入,但我无法在附加文件中写入文件,只能使用adSaveCreateOverWrite".
Write correctly in utf-8 but I can't write the file in appending but only with "adSaveCreateOverWrite".
我该怎么做?还有其他方法吗?
How can I do that? Is there another way?
非常感谢.
推荐答案
您可以将二进制 I/O 与 API 调用结合起来执行到 UTF-8 的转换:
You could combine binary I/O with an API call to perform the conversion to UTF-8:
Option Explicit
Private Const CP_UTF8 As Long = 65001
Private Declare Function WideCharToMultiByte Lib "kernel32" ( _
ByVal CodePage As Long, _
ByVal dwFlags As Long, _
ByVal lpWideCharStr As Long, _
ByVal cchWideChar As Long, _
ByVal lpMultiByteStr As Long, _
ByVal cchMultiByte As Long, _
ByVal lpDefaultChar As Long, _
ByVal lpUsedDefaultChar As Long) As Long
Private Function OpenAppendUTF8(ByVal FileName As String) As Integer
OpenAppendUTF8 = FreeFile(0)
Open FileName For Binary Access Write As #OpenAppendUTF8
Seek #OpenAppendUTF8, LOF(OpenAppendUTF8) + 1
End Function
Private Sub WriteUTF8( _
ByVal FNum As Integer, _
ByVal Text As String, _
Optional ByVal NL As Boolean)
Dim lngResult As Long
Dim UTF8() As Byte
If NL Then Text = Text & vbNewLine
lngResult = WideCharToMultiByte(CP_UTF8, 0, StrPtr(Text), Len(Text), _
0, 0, 0, 0)
If lngResult > 0 Then
ReDim UTF8(lngResult - 1)
WideCharToMultiByte CP_UTF8, 0, StrPtr(Text), Len(Text), _
VarPtr(UTF8(0)), lngResult, 0, 0
Put #FNum, , UTF8
End If
End Sub
Private Sub Main()
Dim F As Integer
F = OpenAppendUTF8("test.txt")
WriteUTF8 F, "Hello"
WriteUTF8 F, ChrW$(&H2026&)
WriteUTF8 F, "World", True
Close #F
MsgBox "Done"
End Sub
这篇关于在 VB6 中追加写入文本文件(utf-8 编码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!