How do I write out a text file in C# with a code page other than UTF-8?
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.
Simple!
System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));
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