vb.net 判断文件编码的方法

前端之家收集整理的这篇文章主要介绍了vb.net 判断文件编码的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
vb.net 判断文件编码的三种方法
使用方法GetEncoding(文件名)
' 读取文本文件内容
'
' 文件
' 文件编码

Public Function ReadFile(ByVal fileName As String) As String
If File.Exists(fileName) Then
Return File.ReadAllText(fileName,GetEncoding(fileName))
Else
Return string.Empty
End If
End Function
'
' 判断文件编码类型
'
'
'
Public Overloads Shared Function GetEncoding(ByVal fileName As String) As Encoding
Dim fs As FileStream = New FileStream(fileName,FileMode.Open,FileAccess.Read)
Dim r As Encoding = GetEncoding(fs)
fs.Close
Return r
End Function
'
' 判断文件流编码类型
'
'

Private Overloads Shared Function GetEncoding(ByVal fs As FileStream) As Encoding
Dim r As BinaryReader = New BinaryReader(fs,System.Text.Encoding.Default)
Dim ss() As Byte = r.ReadBytes(3)
r.Close
If (ss(0) >= 239) Then
BF
Return Encoding.UTF8
If ((ss(0) = 254) _
AndAlso (ss(1) = 255)) Then
Return Encoding.BigEndianUnicode
ElseIf ((ss(0) = 255) _
AndAlso (ss(1) = 254)) Then
Return Encoding.Unicode
Else
Return Encoding.Default
End If
Else
Return Encoding.Default
End If
End Function

猜你在找的VB相关文章