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

后端 未结 5 443
一生所求
一生所求 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:40

    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.

提交回复
热议问题