您的位置:首页 > 编程语言 > VB

自动识别文字的编码以及读取所有文本——VB2005

2009-11-16 20:35 399 查看
在VB2005中,读取文本文件中的文本可以采用的方法是System.IO.File.ReadAllText,这个函数有两个参数,一个是文件的文件名(包含路径);一个是文本的编码,如果省略,采用系统默认的编码。可是,一般的文本编码有ANSI、Unicode、UTF8等。如果编码的格式选择不对,则读出来是一段乱码。
笔者依照网上的资料,编写一个函数,能自动根据判别文本的编码格式,首先是将文本文件的数据读到字节数组中,再判别文本的编码格式,最后将字节数组转化为文本。
Public Shared Function ReturnEncoding(ByVal tB() As Byte) As System.Text.Encoding
Dim tB1 As Byte, tB2 As Byte, tB3 As Byte, tB4 As Byte
If tB.Length < 2 Then Return Nothing
tB1 = tB(0)
tB2 = tB(1)
If tB.Length >= 3 Then tB3 = tB(2)
If tB.Length >= 4 Then tB4 = tB(3)
If (tB1 = &HFE AndAlso tB2 = &HFF) Then Return System.Text.Encoding.BigEndianUnicode
If (tB1 = &HFF AndAlso tB2 = &HFE AndAlso tB3 <> &HFF) Then Return System.Text.Encoding.Unicode
If (tB1 = &HEF AndAlso tB2 = &HBB AndAlso tB3 = &HBF) Then Return System.Text.Encoding.UTF8
Return System.Text.Encoding.Default
End Function


Public Shared Function ByteToText(ByVal mByte() As Byte) As String
Dim tE As System.Text.Encoding = ReturnEncoding(mByte)
Return tE.GetString(mByte)
End Function
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: