转换文本编码
代码
1 /// <summary>
2 /// 将文本转化为Unicode编码(自适应4种编码)
3 /// </summary>
4 /// <param name="fileName"></param>
5 /// <returns></returns>
6 public void ConvertTextToUnicode(string fileName)
7 {
8 Encoding encoding = null;
9 FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read);
10 BinaryReader br = new BinaryReader(fs);
11 byte[] bs = br.ReadBytes(3); // 读文件的前个字节
12 br.Close();
13 fs.Close();
14
15 // 确定编码
16 if (bs.Length > 0)
17 {
18 if (bs[0] == 0xEF && bs[1] == 0xBB && bs[2] == 0xBF)
19 {
20 encoding = Encoding.UTF8;
21 }
22 else if (bs[0] == 0xFF && bs[1] == 0xFE)
23 {
24 //encoding = Encoding.Unicode;
25 return;
26 }
27 else if (bs[0] == 0xFE && bs[1] == 0xFF)
28 {
29 encoding = Encoding.BigEndianUnicode;
30 }
31 }
32
33 string text = File.ReadAllText(fileName, encoding ?? Encoding.Default); // 读取文本
34 File.WriteAllText(fileName, text, Encoding.Unicode);
35 }
2 /// 将文本转化为Unicode编码(自适应4种编码)
3 /// </summary>
4 /// <param name="fileName"></param>
5 /// <returns></returns>
6 public void ConvertTextToUnicode(string fileName)
7 {
8 Encoding encoding = null;
9 FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read);
10 BinaryReader br = new BinaryReader(fs);
11 byte[] bs = br.ReadBytes(3); // 读文件的前个字节
12 br.Close();
13 fs.Close();
14
15 // 确定编码
16 if (bs.Length > 0)
17 {
18 if (bs[0] == 0xEF && bs[1] == 0xBB && bs[2] == 0xBF)
19 {
20 encoding = Encoding.UTF8;
21 }
22 else if (bs[0] == 0xFF && bs[1] == 0xFE)
23 {
24 //encoding = Encoding.Unicode;
25 return;
26 }
27 else if (bs[0] == 0xFE && bs[1] == 0xFF)
28 {
29 encoding = Encoding.BigEndianUnicode;
30 }
31 }
32
33 string text = File.ReadAllText(fileName, encoding ?? Encoding.Default); // 读取文本
34 File.WriteAllText(fileName, text, Encoding.Unicode);
35 }