Encode text by using Encoding classes

Overview

  • Provides information about Encodings.
  • Default .NET Encoding is UTF-16.
  • Notepad has trouble displaying UTF-7 and UTF-32 encoded files, even though the file has been properly encoded.
  • Remember to specify the Encoding when reading a file!

Good practice

  • When in doubt, accept the default UTF-16 encoding.

Examples

Get Available Encodings

EncodingInfo[] e = Encoding.GetEncodings();
 
foreach (var enc in e)
{
    Console.WriteLine("{0}: {1}, {2}", enc.CodePage, enc.Name, enc.DisplayName);
}

Check Different Encodings

StreamWriter u7 = new StreamWriter(@"C:\Public\u7.txt", false, Encoding.UTF7);
StreamWriter u8 = new StreamWriter(@"C:\Public\u8.txt", false, Encoding.UTF8);
StreamWriter u16 = new StreamWriter(@"C:\Public\u16.txt", false, Encoding.Unicode);
StreamWriter u32 = new StreamWriter(@"C:\Public\u32.txt", false, Encoding.UTF32);
 
string hello = "Hello, World!";
u7.Write(hello);
u8.Write(hello);
u16.Write(hello);
u32.Write(hello);
 
u7.Close();
u8.Close();
u16.Close();
u32.Close();
 
// Now view each file in Notepad, and it's properties for the size