2012年5月21日 星期一

vb6 utf8 to ansi


根据反馈,代码已作修改并调试通过:

分二步:
一、建立一个模块,复制下面代码
Option Explicit
Private Declare Function MultiByteToWideChar Lib "kernel32" (ByVal CodePage As Long, ByVal dwFlags As Long, ByRef lpMultiByteStr As Any, ByVal cchMultiByte As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long) As Long
Private Const CP_UTF8 = 65001

'读文件至变量
Private Function GetFile(FileName As String) As String
Dim i As Integer, BB() As Byte
    If Dir(FileName) = "" Then Exit Function
    i = FreeFile
    ReDim BB(FileLen(FileName) - 1)
    Open FileName For Binary As #i
    Get #i, , BB
    Close #i
    GetFile = BB
End Function

'功能: 把Utf8字符转化成ANSI字符
Public Function UTF8_Decode(FileName As String) As String
Dim sUTF8 As String
Dim lngUtf8Size As Long
Dim strBuffer As String
Dim lngBufferSize As Long
Dim lngResult As Long
Dim bytUtf8() As Byte
Dim n As Long
    sUTF8 = GetFile(FileName)
    If LenB(sUTF8) = 0 Then Exit Function
    On Error GoTo EndFunction
    bytUtf8 = sUTF8
    lngUtf8Size = UBound(bytUtf8) + 1
    lngBufferSize = lngUtf8Size * 2
    strBuffer = String$(lngBufferSize, vbNullChar)
    lngResult = MultiByteToWideChar(CP_UTF8, 0, bytUtf8(0), _
            lngUtf8Size, StrPtr(strBuffer), lngBufferSize)
    If lngResult Then
        UTF8_Decode = Left(strBuffer, lngResult)
    End If
EndFunction:
 
End Function

二、调用举例:
如果你想把一个"c:\1.txt"的UTF-8文件转换为ANSI编码,可这样调用
dim s as string
s=UTF8_Decode("c:\1.txt") '文件名请根据实际修改
此时,s存放的就是ANSI格式编码了,不会出现乱码问题

沒有留言:

張貼留言