Friday, July 5, 2013

Write UTF8-Encoded Text File using C#

Using C# to generate html file that use language-specific encoding can avoid some characters (e.g. characters in Arab or Chinese) from reading wrongly by other application which use UTF8 encoding to read. The simple way to do this is to include Encoding.UTF8 in the StreamWriter constructor. Below shows an example of how to do this:

    using (StreamWriter writer = new StreamWriter(new FileStream(filename, FileMode.CreateNew, FileAccess.Write), Encoding.UTF8))
            {

                writer.WriteLine("大家好");
                writer.Flush();
            }

No comments:

Post a Comment