C#指定编码写文件的那些事

来源:互联网 发布:ipad 淘宝卖家 编辑:程序博客网 时间:2024/05/10 00:24
本文转自http://www.2cto.com/kf/201311/255296.html

C#写文件时,StreamWriter有可选参数指定编码格式Encoding,而文件的格式ASCII,UTF-8,UTF-32,Unicode,gb2312对于存储文件内容又格外重要。(关于具体文件编码请上网搜索资料)

测试代码如下:
 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO; 
   
namespaceTest 
    classProgram 
    
        staticvoid Main(string[] args) 
        
            try 
            
   
                StreamWriter sw1 =new StreamWriter("1.txt"); 
                StreamWriter sw2 =new StreamWriter("2.txt",false, Encoding.GetEncoding("ASCII")); 
                StreamWriter sw3 =new StreamWriter("3.txt",false, Encoding.GetEncoding("UTF-8")); 
                StreamWriter sw4 =new StreamWriter("4.txt",false, Encoding.GetEncoding("UTF-7")); 
                StreamWriter sw5 =new StreamWriter("5.txt",false, Encoding.GetEncoding("UTF-32")); 
                StreamWriter sw6 =new StreamWriter("6.txt",false, Encoding.GetEncoding("Unicode")); 
                StreamWriter sw7 =new StreamWriter("7.txt",false, Encoding.GetEncoding("GB2312")); 
                   
   
                sw1.WriteLine("test 测试"); 
                sw2.WriteLine("test 测试"); 
                sw3.WriteLine("test 测试"); 
                sw4.WriteLine("test 测试"); 
                sw5.WriteLine("test 测试"); 
                sw6.WriteLine("test 测试"); 
                sw7.WriteLine("test 测试"); 
   
                sw1.Close(); 
                sw2.Close(); 
                sw3.Close(); 
                sw4.Close(); 
                sw5.Close(); 
                sw6.Close(); 
                sw7.Close(); 
            
            catch(IOException) 
            {  
               
            
   
        
    
}

 

 
 
运行结果:
生成7个文件,在Notepad++中显示相应文件编码如下:
1.txt  ANSI as UTF-8
内容显示为: test 测试
文件大小:13字节
 
2.txt  ANSI as UTF-8
内容显示为: test ??
文件大小:9字节
 
3.txt  UTF-8
内容显示为: test 测试
文件大小:16字节
 
4.txt  ANSI as UTF-8
内容显示为: test +bUuL1Q-
文件大小:15字节
 
5.txt  UCS-Little Endian
内容显示为: test 测试
文件大小:40字节
 
6.txt  UCS-Little Endian
内容显示为: test 测试
文件大小:20字节
 
7.txt  ANSI
内容显示为: test 测试
文件大小:11字节
0 0
原创粉丝点击