Write Unicode String In a File Using StreamWriter doesn't Work

ahmadali shafiee picture ahmadali shafiee · Nov 19, 2011 · Viewed 36.8k times · Source

I have this code:

string s = "آ";
StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8);
writer.WriteLine(s);

but when I run it I can't see any "آ" in a.txt!! There isn't any string in a.txt! It is Empty! What is problem!?! Can anyone help me???

Answer

Oded picture Oded · Nov 19, 2011

You never Close() the StreamWriter.

If you call writer.Close() when you finish writing, you will see the character.

But, since it implements IDisposable you should wrap the creation of the StreamWriter in a using statement:

using(StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8))
{
   writer.WriteLine(s);
}

This will close the stream for you.