Tuesday, October 16, 2012

Encoding and Decoding in .Net

The following is an example of how to go from one Encoding to another, and how to handle unavailable characters.


Encoding cp1252r = Encoding.GetEncoding(Encoding.ASCII.EncodingName,
                                        new EncoderReplacementFallback("*"),
                                        new DecoderReplacementFallback("*"));

 string str1 = " Hello \u24C8 \u2075 \u221E World";
 string str2 = cp1252r.GetString(cp1252r.GetBytes(str1));

 Console.WriteLine(" Before: {0} After: {1} ", str1,str2);


In the above example the missing character are replaced by asterisks. 


Encoding cp1252r = Encoding.GetEncoding(Encoding.ASCII.EncodingName,
                                        new EncoderExceptionFallback(),
                                        new DecoderExceptionFallback());

 string str1 = " Hello \u24C8 \u2075 \u221E World";
 string str2 = cp1252r.GetString(cp1252r.GetBytes(str1));

 Console.WriteLine(" Before: {0} After: {1} ", str1,str2);

Here, an exception will be thrown.

Reference: http://msdn.microsoft.com/en-us/library/ms404377.aspx

No comments: