Sunday, March 6, 2011

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

I'm writing out my file with the following very simple code:

using (StreamWriter sw = File.CreateText(myfilename))
{

    sw.WriteLine("my text...");
    sw.Close();
}

?

Thanks!

-Adeena

From stackoverflow
  • Change the Encoding of the stream writer. It's a property.

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

    So:

    sw.Encoding = Encoding.GetEncoding(28591);
    

    Prior to writing to the stream.

    Daniel Crenna : That property is readonly.
  • 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.

    Steven Behnke : Good point that you could do it in the constructor as well.
    adeena : Can "whatever I want" be a code page number or...? the autocomplete on the function in MS Visual C# isn't giving me an "iso-8859-1" option... just the UTF8, UTF16, etc...
  • Simple!

    System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));
    

0 comments:

Post a Comment