-
本文转自http://www.2cto.com/kf/201311/255296.html
-
C#写文件时,StreamWriter有可选参数指定编码格式Encoding,而文件的格式ASCII,UTF-8,UTF-32,Unicode,gb2312对于存储文件内容又格外重要。(关于具体文件编码请上网搜索资料)
测试代码如下:12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849using
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字节
C#指定编码写文件的那些事
最新推荐文章于 2024-01-03 15:35:01 发布