如何获取一个文件的编码方式

Unicode & BOM

 

 System.Text.Encoding enc = null;

            using (System.IO.FileStream file = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                if (file.CanSeek)
                {
                    byte[] bom = new byte[4]; // Get the byte-order mark, if there is one 
                    file.Read(bom, 0, 4);

                    if(bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf)
                    {
                        enc = System.Text.Encoding.UTF8;  
                    }
                    else if (bom[0] == 0xff && bom[1] == 0xfe)
                    {
                        // ucs-2le, ucs-4le, and ucs-16le
                        enc=System.Text.Encoding.Unicode;
                    }
                    else if(bom[0] == 0xfe && bom[1] == 0xff) 
                    {
                        // utf-16 and ucs-2
                        enc=System.Text.Encoding.BigEndianUnicode;
                    }
                    else if(bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) 
                    {
                        // ucs-4
                        enc = System.Text.Encoding.UTF32;                        
                    }
                    else
                    {
                        enc = System.Text.Encoding.ASCII;
                    }
                }
                else
                {
                    // The file cannot be randomly accessed, so you need to decide what to set the default to
                    // based on the data provided. If you're expecting data from a lot of older applications,
                    // default your encoding to Encoding.ASCII. If you're expecting data from a lot of newer
                    // applications, default your encoding to Encoding.Unicode. Also, since binary files are
                    // single byte-based, so you will want to use Encoding.ASCII, even though you'll probably
                    // never need to use the encoding then since the Encoding classes are really meant to get
                    // strings from the byte array that is the file.
                    enc = System.Text.Encoding.ASCII;
                }
                return enc;
            }

转载于:https://www.cnblogs.com/lubing/archive/2009/09/02/1558534.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值