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

本文介绍了在C#中使用StreamWriter类写入文件时,通过指定不同编码(如ASCII, UTF-8, UTF-32等)来影响文件存储的内容和格式,并展示了实际操作及结果对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文转自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; 
   
namespace Test 
     class Program 
    
         static void 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字节
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值