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.
- 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
You May Also Like
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



