views:

3734

answers:

3

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

+3  A: 

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.

Steven Behnke
That property is readonly.
Daniel Crenna
+4  A: 
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.

Dave Markle
Good point that you could do it in the constructor as well.
Steven Behnke
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...
adeena
+1  A: 

Simple!

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