How do I write out a text file in C# with a code page other than UTF-8?

后端 未结 5 446
一生所求
一生所求 2020-11-30 03:07

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...

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 03:30

    Wrap your StreamWriter with FileStream, this way:

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

    Look at MSDN

提交回复
热议问题