如何将UCS2-Little Endian中的文件编码为Windows-1251?

时间:2014-07-03 22:07:56

标签: xml vba encoding ucs2

我正在尝试将编码从UCS2-Little Endian中的现有文件更改为Windows-1251中的Visual Basic。

我使用以下代码:

Sub convertFile()
t = AlterCharset("utf-16LE", "windows-1251")

iFileNum = FreeFile
Open sFullPath For Output As #iFileNum
Print #iFileNum, t

Close #iFileNum

End Sub

Private Function AlterCharset(FromChaset, ToCharset)
 Dim Bytes
 Bytes = StringToBytes(FromChaset)
 AlterCharset = BytesToString(Bytes, ToCharset)
End Function

Function StringToBytes(Charset)
 Dim Stream: Set Stream = CreateObject("ADODB.Stream")
 Stream.Type = adTypeText
 Stream.Charset = Charset
 Stream.Open
 Stream.LoadFromFile sFullPath
 Stream.flush
 Stream.Position = 0
 Stream.Type = adTypeBinary
 StringToBytes = Stream.Read
 Stream.Close
 Set Stream = Nothing
End Function

Private Function BytesToString(Bytes, Charset)

 Dim Stream: Set Stream = CreateObject("ADODB.Stream")
 Stream.Charset = Charset
 Stream.Type = adTypeBinary
 Stream.Open
 Stream.Write Bytes
 Stream.flush
 Stream.Position = 0
 Stream.Type = adTypeText
 BytesToString = Stream.ReadText
 Stream.Close
 Set Stream = Nothing

结束功能

问题是我总是在文本的开头得到一些字节而我无法在记事本++中打开它

有人可以看看我的代码中可能出现的问题吗?

1 个答案:

答案 0 :(得分:0)

你可以这样做来阅读UCS2-Little Endian:

Dim fso     : Set fso = CreateObject("Scripting.FileSystemObject")
txt = fso.OpenTextFile("txtfile.txt", 1, False, -1).ReadAll

进入内存后,您可以写入其他文件