Skip to content
David Cumps
Exam 70-536 study notes

Encode text by using Encoding classes

Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).

Overview

  • Provides information about encodings.
  • Strings are UTF-16 internally; StreamWriter and File methods default to UTF-8.
  • 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 encoding.

Examples

Get Available Encodings

EncodingInfo[] e = Encoding.GetEncodings();
 
foreach (EncodingInfo 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 its properties for the size

You May Also Like