[英]How do I write out a text file in C# with a code page other than UTF-8?
I want to write out a text file. 我想写出一个文本文件。
Instead of the default UTF-8, I want to write it encoded as ISO-8859-1 which is code page 28591. I have no idea how to do this... 而不是默认的UTF-8,我想写它编码为ISO-8859-1,这是代码页28591.我不知道如何做到这一点......
I'm writing out my file with the following very simple code: 我用以下非常简单的代码写出我的文件:
using (StreamWriter sw = File.CreateText(myfilename))
{
sw.WriteLine("my text...");
sw.Close();
}
using System.IO;
using System.Text;
using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{
sw.WriteLine("my text...");
}
An alternate way of getting your encoding: 获取编码的另一种方法:
using System.IO;
using System.Text;
using (var sw = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
sw.WriteLine("my text...");
}
Check out the docs for the StreamWriter constructor. 查看StreamWriter构造函数的文档。
简单!
System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));
Wrap your StreamWriter with FileStream, this way: 用FileStream包装StreamWriter,这样:
string fileName = "test.txt";
string textToAdd = "Example text in file";
Encoding encoding = Encoding.GetEncoding("ISO-8859-1"); //Or any other Encoding
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
using (StreamWriter writer = new StreamWriter(fs, encoding))
{
writer.Write(textToAdd);
}
}
You can have something like this 你可以有这样的东西
switch (EncodingFormat.Trim().ToLower())
{
case "utf-8":
File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, new UTF8Encoding(false), convertToCSV(result, fileName)));
break;
case "utf-8+bom":
File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, new UTF8Encoding(true), convertToCSV(result, fileName)));
break;
case "ISO-8859-1":
File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, Encoding.GetEncoding("iso-8859-1"), convertToCSV(result, fileName)));
break;
case ..............
}
Change the Encoding of the stream writer. 更改流编写器的编码。 It's a property.
这是一个属性。
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.encoding.aspx http://msdn.microsoft.com/en-us/library/system.io.streamwriter.encoding.aspx
So: 所以:
sw.Encoding = Encoding.GetEncoding(28591);
Prior to writing to the stream. 在写入流之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.