55

我想写出一个文本文件。

而不是默认的 UTF-8,我想将其编码为 ISO-8859-1,即代码页 28591。我不知道该怎么做......

我正在用以下非常简单的代码写出我的文件:

using (StreamWriter sw = File.CreateText(myfilename))
{
    sw.WriteLine("my text...");
    sw.Close();
}
4

5 回答 5

90
using System.IO;
using System.Text;

using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{    
    sw.WriteLine("my text...");     
}

获取编码的另一种方法:

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...");             
}

查看 StreamWriter 构造函数的文档。

于 2008-12-17T01:11:43.957 回答
36

简单的!

System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));
于 2009-01-03T21:49:52.467 回答
4

用 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);
    }
}

看看 MSDN

于 2014-04-28T16:54:56.847 回答
0

你可以有这样的东西

 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 ..............
    }
于 2019-08-30T12:42:05.240 回答
-4

更改流编写器的编码。这是一个财产。

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.encoding.aspx

所以:

sw.Encoding = Encoding.GetEncoding(28591);

在写入流之前。

于 2008-12-17T01:08:28.410 回答