Reputation: 138
I am having an issue with my file output. I need to write to a file the character ý and þ. I can do this using Convert.ToChar(0253) & Convert.ToChar(0254). This is an old program that I have rewritten in C# from basic+. The old program created a simple text file that if opened in wordpad would render the special characters ý & þ. However, when I create the file and open it in wordpad it renders the characters as ý and þ. Below is the output file opened in both notepad and wordpad. How can I output the characters so that they will render as ý and þ in both notepad and wordpad? I have also inserted my code below. Thanks in advance.
This renders fine in notepad like so:
3/31/2015ý15þ
14182515þ
ENDþ
However, when opening the file in wordpad it renders like this:
3/31/2015ý15þ
14182515þ
ENDþ
textOut.WriteLine(shortDate + Convert.ToChar(0253) + cRenPer + Convert.ToChar(0254));
Upvotes: 0
Views: 910
Reputation: 138
So, as Thorsten Dittmar had suggested I needed to encode the stream-writer as utf8. This allowed the file to be read by the preexisting application as it should be. Below is the change to the stream-writer class.
StreamWriter textOut = new StreamWriter((dirPath + batchNum + ".REN"), false, new UTF8Encoding(true));
This is an edit: I ended up modifying the code. Although the text file ended up being interpreted correctly in word-pad it was still not being read by the legacy application. My modified code is below:
StreamWriter textOut = new StreamWriter(new FileStream((dirPath + batchNum + ".REN"),
FileMode.Create, FileAccess.Write),
System.Text.UnicodeEncoding.Default);
Upvotes: 1
Reputation: 56697
You should specify either UTF8 or UTF16 encoding when writing the file. You can do it like this:
StreamWriter writer = new StreamWriter(<file path>, false, Encoding.UTF8);
Upvotes: 2
Reputation: 43300
You can set the encoding when you define the streamreader
StreamWriter textOut = new StreamWriter(new FileStream((dirPath + batchNum + ".REN"),
FileMode.Create, FileAccess.Write),
Encoding.UTF8);
Upvotes: 1
Reputation: 758
You could write to file using the following code , note the 2nd encoding parameter. This will effect how the file is encoded , which in turn will effect how will ite will be treated by various text editors.
string fileName = "myFile.txt";
using (TextWriter textOut = new StreamWriter(File.OpenWrite(fileName),System.Text.Encoding.Unicode))
{
textOut.WriteLine(Convert.ToChar(0254));
}
Upvotes: 0