赞
踩
TXT文件共4种类型编码:GB3212、UTF8、BIG UTF8、Unicode
*****************下为以C#代码****************
public System.Text.Encoding TXT_EncodeType(string filename)
{
System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
Byte[] buffer = br.ReadBytes(2);
if (buffer[0] >= 0xEF)
{
if (buffer[0] == 0xEF && buffer[1] == 0xBB)
{
return System.Text.Encoding.UTF8;
}
else if (buffer[0] == 0xFE && buffer[1] == 0xFF)
{
return System.Text.Encoding.BigEndianUnicode;
}
else if (buffer[0] == 0xFF && buffer[1] == 0xFE)
{
return System.Text.Encoding.Unicode;
}
else
{
return System.Text.Encoding.Default;
}
}
else
{
return System.Text.Encoding.Default;
}
}
调取代码
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show( TXT_EncodeType("d:\\xxxx.txt").EncodingName);
}
}
*****************下为vb.net 代码**********************
调取代码
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show(TXT_EncodeType("d:\xxxx.txt").EncodingName)
End Sub
'返回txt文件编码方式
Public Function TXT_EncodeType(ByVal filename As String) As System.Text.Encoding
Using fs As System.IO.FileStream = New System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim br As System.IO.BinaryReader = New System.IO.BinaryReader(fs)
Dim buffer() As Byte = br.ReadBytes(2)
If buffer(0) >= &HEF Then '239
'&H 表示16进制数,放在开头 如:&HFF
If (buffer(0) = &HEF) AndAlso (buffer(1) = &HBB) Then
Return System.Text.Encoding.UTF8
ElseIf (buffer(0) = &HFE AndAlso buffer(1) = &HFF) Then
Return System.Text.Encoding.BigEndianUnicode
ElseIf (buffer(0) = &HFF AndAlso buffer(1) = &HFE) Then
Return System.Text.Encoding.Unicode
Else
Return System.Text.Encoding.Default
End If
Else
Return System.Text.Encoding.Default
End If
End Using
End Function
记录下
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。