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(); }
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.
You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a 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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With