用以下两种方式写文件时,都是默认使用的UTF-8格式的编码
string csFileName = ""; //文件名,完整路径
string html = ""; //文件内容
//方法一
using (StreamWriter sww = File.CreateText(csFileName)) {
sww.Write(html);
sww.Flush();
}
//方法二
FileInfo file = new FileInfo(csFileName);
using (StreamWriter sww = file.CreateText()) {
sww.Write(html);
sww.Flush();
}
以上两种CreateText方法都是使用UTF-8编码,并且没有办法指定编码。但是StreamWriter的构造函数中可以指定编码格式,所以可以使用下面的方法,实现用GB2312编码写文件的需求。string html = ""; //文件内容
//方法一
using (StreamWriter sww = File.CreateText(csFileName)) {
sww.Write(html);
sww.Flush();
}
//方法二
FileInfo file = new FileInfo(csFileName);
using (StreamWriter sww = file.CreateText()) {
sww.Write(html);
sww.Flush();
}
/// <summary>
/// 将字符串写入指定的文件中
/// </summary>
/// <param name="path">文件名,完整路径</param>
/// <param name="source">要写入文件的字符串</param>
private void WriteFile(string path, string source){
using(StreamWriter writer = new StreamWriter(path, false, Encoding.GetEncoding("GB2312"), 512)){
writer.Write(source);
writer.Flush();
}
}
/// 将字符串写入指定的文件中
/// </summary>
/// <param name="path">文件名,完整路径</param>
/// <param name="source">要写入文件的字符串</param>
private void WriteFile(string path, string source){
using(StreamWriter writer = new StreamWriter(path, false, Encoding.GetEncoding("GB2312"), 512)){
writer.Write(source);
writer.Flush();
}
}