vb6处理utf8编解码有至少4种方法:
- 基于API实现(createfile setfilepointer (ex))
- 基于ADODB.Stream组件实现
- 基于XML组件实现
- 纯VB6代码实现
先搞个处理字符串的utf8编码和解码,本实例使用 基于ADODB.Stream组件实现
字符串处理
'* ************************************** *
'* 模块名称:modCharset.bas
'* 模块功能:GB2312与UTF8相互转换函数
'* 作者:lyserver
'* ************************************** *
Option Explicit
'- ------------------------------------------- -
' 函数说明:GB2312转换为UTF8
'- ------------------------------------------- -
Public Function GB2312ToUTF8(strIn As String, Optional ByVal ReturnValueType As VbVarType = vbString) As Variant
Dim adoStream As Object
Set adoStream = CreateObject("ADODB.Stream")
adoStream.Charset = "utf-8"
adoStream.Type = 2 'adTypeText
adoStream.Open
adoStream.WriteText strIn
adoStream.Position = 0
adoStream.Type = 1 'adTypeBinary
GB2312ToUTF8 = adoStream.Read()
adoStream.Close
If ReturnValueType = vbString Then GB2312ToUTF8 = Mid(GB2312ToUTF8, 1)
End Function
'- ------------------------------------------- -
' 函数说明:UTF8转换为GB2312
'- ------------------------------------------- -
Public Function UTF8ToGB2312(ByVal varIn As Variant) As String
Dim bytesData() As Byte
Dim adoStream As Object
bytesData = varIn
Set adoStream = CreateObject("ADODB.Stream")
adoStream.Charset = "utf-8"
adoStream.Type = 1 'adTypeBinary
adoStream.Open
adoStream.Write bytesData
adoStream.Position = 0
adoStream.Type = 2 'adTypeText
UTF8ToGB2312 = adoStream.ReadText()
adoStream.Close
End Function
文件处理
Rem 工程要引用 Microsoft ActiveX Data Objects 2.8,下面的通用方法建议放在模块中
Public Sub SaveAsUTF8(ByVal Text As String, ByVal FileName As String)
Dim oStream As ADODB.Stream
Set oStream = New ADODB.Stream
oStream.Open
oStream.Charset = "UTF-8"
oStream.Type = adTypeText
oStream.WriteText Text
oStream.SaveToFile FileName, adSaveCreateOverWrite
oStream.Close
End Sub
Public Function LoadAsUTF8(ByVal FileName As String) As String
Dim oStream As ADODB.Stream
Set oStream = New ADODB.Stream
oStream.Open
oStream.Charset = "UTF-8"
oStream.LoadFromFile FileName
LoadAsUTF8 = oStream.ReadText()
oStream.Close
End Function
createfile readfile 读入后对这些数据要进行编码转换就是 MultiByteToWideChar WideCharToMultiByte , 完全可以替换掉adodb.stream
Views: 109