Encoding

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 nameStatic property on Encoding
UTF-8Encoding.UTF8
UTF-16Encoding.Unicode
UTF-32Encoding.UTF32
ASCIIEncoding.ASCII

Character-Encoding Classes

Encoding SchemeClassCreate Using
ASCIIASCIIEncodingGetEncoding ASCII property
DefaultEncodingGetEncoding Default property
UTF-7UTF7EncodingGetEncoding UTF7 property
UTF-8UTF8EncodingGetEncoding UTF8 property
UTF-16 (big-endian)UnicodeEncodingGetEncoding BigEndianUnicode property
UTF-16 (little-endian)UnicodeEncodingGetEncoding Unicode property
Windows OSEncodingGetEncoding(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));
        }

    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.