我必须在VB6中编写一个文本文件.我需要附加和utf-8编码.
我尝试了两个解决方案,一个使用“TextStream”,另一个使用“ADODB.Stream”.
第一个:
Set fsoFile = fso.OpenTextFile(FileIn(fi),ForAppending,True) fsoFile.WriteLine "<tag>kkkjòòkkkkjlòlk</tag>" fsoFile.Close
附加效果不错,但我如何编写utf-8编码?
第二个:
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”.
我怎样才能做到这一点?还有另一种方式吗?
非常感谢你.
您可以将二进制I / O与API调用结合使用以执行到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,StrPtr(Text),Len(Text),_ 0,0) If lngResult > 0 Then ReDim UTF8(lngResult - 1) WideCharToMultiByte CP_UTF8,_ VarPtr(UTF8(0)),lngResult,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