' 获取文件编码,原C#编码,本人改写为VB.NET代码
' 原文:http://www.devbook.cn/newsdetail.aspx?news_pkid=N100008
' 本人主页:https://clso.fun
Imports System.Text, System.IO
''' <summary>用于取得一个文本文件的编码方式(Encoding)</summary>
Public Class TxtFileEncoding
''' <summary>用于取得一个文本文件的编码方式(Encoding)</summary>
Shared Function GetEncoding(ByVal filePath As String) As Encoding
Return GetEncoding(File.OpenRead(filePath), Encoding.Default)
End Function
''' <summary>用于取得一个文本文件的编码方式(Encoding)</summary>
Shared Function GetEncoding(ByVal stream As FileStream, ByVal defaultEncoding As Encoding) As Encoding
Dim targetEncoding As Encoding = defaultEncoding
If stream IsNot Nothing AndAlso stream.Length >= 2 Then
' 保存文件流的前4个字节
Dim b1 As Byte = 0, b2 As Byte = 0, b3 As Byte = 0, b4 As Byte = 0
' 保存当前Seek位置
Dim origPos As Long = stream.Seek(0, SeekOrigin.Begin)
stream.Seek(0, SeekOrigin.Begin)
Dim nByte As Integer = stream.ReadByte
b1 = nByte
b2 = stream.ReadByte
If stream.Length >= 3 Then b3 = stream.ReadByte
If stream.Length >= 4 Then b4 = stream.ReadByte
' 根据文件流的前4个字节判断Encoding
' Unicode {0xFF, 0xFE};
' BE-Unicode {0xFE, 0xFF};
' UTF8 = {0xEF, 0xBB, 0xBF};
If b1 = &HFE And b2 = &HFE Then targetEncoding = Encoding.BigEndianUnicode
If b1 = &HEF And b2 = &HEF Then targetEncoding = Encoding.UTF8
' 恢复Seek位置
stream.Seek(origPos, SeekOrigin.Begin)
End If
Return targetEncoding
End Function
End Class