如何获取一个文件的编码方式
2009-09-02 02:02
281 查看
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; }
相关文章推荐
- Linux下如何查看一个文件,如temp.txt 内容的编码方式?
- 如何修改自己eclipse工程中新建一个jsp文件的编码方式呢
- 如何修改自己eclipse工程中新建一个jsp文件的编码方式呢
- 如何使用Java代码获取文件、文件流或字符串的编码方式
- 如何用DOS命令,获取一个目录下的文件数目
- 如何使用gcore工具获取一个core文件而不重启应用?
- iphone阅读器,如果要读取一个文本文件,请问你是如何处理编码问题的?另外像pdf格式的文件,你如何读取。?
- 【iOS开发-3】sandbox沙盒介绍以及如何取得沙盒里面各文件的路径,图片导入方式和图片路径获取
- 在nodejs中如何用异步的方式读取一个文件
- Java如何获取文件编码格式
- 在一个Android项目里面有两个可运行文件,如何实现调用方式
- C#如何获取快捷方式指向的目标文件
- Java如何获取文件编码格式
- JAVA 程序中如何拷贝一个目录下的文件及子目录到另一个目录,如何获取系统环境变量等...
- 如何判断一个文件的编码格式是gb2312还是gbk等
- Java如何获取文件编码格式
- 如何用DOS命令,获取一个目录下的文件数目
- 如何判断文件的编码方式
- 如何获取一个文件后缀?
- 如何进行编码和通过 Visual C# InfoPath 中以编程方式解码文件附件