Friday, July 5, 2013

Write UTF8-Encoded HTML 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 displaying wrong in web browser. The simple way to do this is to include Encoding.UTF8 in the StreamWriter constructor and include "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" in the header of the html page being written. 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("<html>");
                writer.WriteLine("<header>");
                writer.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
                writer.WriteLine("</header>");
                writer.WriteLine("<body>");
             
                writer.WriteLine("</body></html>");
                writer.Flush();
            }

No comments:

Post a Comment