System.Text.Encoding contains the command used encoding information.
The abstract class Encoding and its concrete subclasses provide a variety of encoding schemes.
The common encodings:
Encoding name Static property on Encoding
UTF-8 Encoding.UTF8
UTF-16 Encoding.Unicode
UTF-32 Encoding.UTF32
ASCII Encoding.ASCII
Character-Encoding Classes
Encoding Scheme Class Create Using
ASCII ASCIIEncoding GetEncoding ASCII property
Default Encoding GetEncoding Default property
UTF-7 UTF7Encoding GetEncoding UTF7 property
UTF-8 UTF8Encoding GetEncoding UTF8 property
UTF-16 (big-endian) UnicodeEncoding GetEncoding BigEndianUnicode property
UTF-16 (little-endian) UnicodeEncoding GetEncoding Unicode property
Windows OS Encoding GetEncoding(1252)
using System;
using System.Text;
class Sample
{
public static void Main()
{
Encoding utf8 = Encoding.GetEncoding("utf-8");
Encoding chinese = Encoding.GetEncoding("GB18030");
}
}
The following example demonstrates the use of some encoding classes:
using System;
using System.IO;
using System.Text;
class MainClass
{
public static void Main()
{
using (StreamWriter output = new StreamWriter("output.txt"))
{
// Create and write a string containing the symbol for pi.
string srcString = "Area = \u03A0r^2";
output.WriteLine("Source Text : " + srcString);
// Write the UTF-16 encoded bytes of the source string.
byte[] utf16String = Encoding.Unicode.GetBytes(srcString);
output.WriteLine("UTF-16 Bytes: {0}",
BitConverter.ToString(utf16String));
// Convert the UTF-16 encoded source string to UTF-8 and ASCII.
byte[] utf8String = Encoding.UTF8.GetBytes(srcString);
byte[] asciiString = Encoding.ASCII.GetBytes(srcString);
// Write the UTF-8 and ASCII encoded byte arrays.
output.WriteLine("UTF-8 Bytes: {0}",
BitConverter.ToString(utf8String));
output.WriteLine("ASCII Bytes: {0}",
BitConverter.ToString(asciiString));
// Convert UTF-8 and ASCII encoded bytes back to UTF-16 encoded
// string and write.
output.WriteLine("UTF-8 Text : {0}",
Encoding.UTF8.GetString(utf8String));
output.WriteLine("ASCII Text : {0}",
Encoding.ASCII.GetString(asciiString));
}
}
}