Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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(); } 
like image 917
adeena Avatar asked Dec 17 '08 01:12

adeena


People also ask

How do you write to a file in C?

For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf() . The only difference is that fprintf() and fscanf() expects a pointer to the structure FILE.

How do you write a string of text into a file in C?

You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.

How do I write in a TXT file?

Steps for writing to text files First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.


2 Answers

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.

like image 92
Dave Markle Avatar answered Sep 29 '22 01:09

Dave Markle


Simple!

System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591)); 
like image 36
Johann Gerell Avatar answered Sep 29 '22 00:09

Johann Gerell