高分求-VB 把ANSI文本转换成UTF-8,多谢!!

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了高分求-VB 把ANSI文本转换成UTF-8,多谢!!相关的知识,希望对你有一定的参考价值。

比如在F盘的TEMP文件夹里有一个A.TXT,其编码为ansi,希望高手帮写个程序,把该文本转换成UFT-8的编码
要求该函数或过程传入的参数是文件的路径,比如传入"f:\temp\a.txt"
然后就会将f:\temp\a.txt转换成UTF-8编码格式的文件,替换掉原先的a.txt
成功后追加100分,不胜感激!
强烈鄙视一楼,首先是你复制来的答案就是我以前找UTF-8转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格式编码了,不会出现乱码问题

参考资料:http://zhidao.baidu.com/question/123224632.html?fr=im2

参考技术A Private Sub AnsiToUtf8 (FileName as String)
Dim b() As Byte, S As String
Dim ADO_Stream As Object
If Dir(FileName) = "" Then Exit Sub
ReDim b(FileLen(FileName))
Open FileName For Binary As #1
Get #1, , b
Close #1
S = StrConv(b, vbUnicode)
Set ADO_Stream = CreateObject("ADODB.Stream")
With ADO_Stream
.Type = 2
.Mode = 3
.Charset = "utf-8"
.open
.WriteText S
.SaveToFile FileName, 2
End With
Set ADO_Stream = Nothing

End Sub

参考资料:http://zhidao.baidu.com/question/83609963.html?si=3

本回答被提问者采纳

以上是关于高分求-VB 把ANSI文本转换成UTF-8,多谢!!的主要内容,如果未能解决你的问题,请参考以下文章

vb中怎么把ansi转换成UTF-8

怎么把UTF-8编码的文本批量改成ANSI啊!!!!!!!!!?

求批处理,把拖入文本都变成UTF-8编码

VB怎么把ANSI编码的txt文件转为UTF-8编码?

如何将txt文本文件的ansi编码转换成utf-8编码

UTF-8批量转ANSI