Jul
04
2002
Reading and writing international characters
Posted by admin under
.NET
For a customer I had to write some code to read and write simple textfiles. Sounds so easy, just put up a textbox and then
string filename="fil.txt";
StreamReader sr = new StreamReader(filename);
StringBuilder sb = new StringBuilder();
string str = sr.ReadLine();
while( str != null )
{
sb.Append(str + "\n");
str = sr.ReadLine();
}
sr.Close();
txtTheTextBox.Text = db.ToString();
It worked right away, and later I added write capabilities, setting txtTheTextBox.ReadOnly to false and showing a 'Update' button as well.
Writing (called on update_Click) looked like this:
string filename="fil.txt";
StreamWriter sw = new StreamWriter(filename, false);
sw.WriteLine(txtTheTextBox.Text);
sw.Close();
While I thought I was done, there was a problem handling swedish characters (Å,Ö,Ö).
I started trying using different encoders to the StreamReader/StreamWrite constructor and with new UTF7Encoding() as last parameter all looked ok again, swedish characters as well.
However, when looking in the file from NotePad sweidh characters were not readable, instead they were replaced by some weird set of characters.
After trying almost every possible variation of encoders, I then tried:
StreamReader sr = new StreamReader(filename,System.Text.Encoding.Default);
and
StreamWriter sw = new StreamWriter(filename, false,System.Text.Encoding.Default);
AND FINALLY! Now reading and writing from ASP.NET as well as from Notepad worked!