当前位置:   article > 正文

TXT 文件编码类型_txt编码格式

txt编码格式

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

记录下

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/373572
推荐阅读
相关标签
  

闽ICP备14008679号