Posts Tagged character encoding

Basic character encoding wrapper class

Posted by Ozer Senturk on Tuesday, 9 March, 2010
using System.Text;

namespace CommonUtils
{
    /// <summary>
    /// Class related with encoding operations
    /// </summary>
    public class Encodings
    {
        /// <summary>
        /// Converts the string str from source encoding to target encoding
        /// </summary>
        /// <param name="str">The string to convert</param>
        /// <param name="source">The cource encoding</param>
        /// <param name="target">The target encoding</param>
        /// <returns>The converted string</returns>
        public static string convertEncoding(string str, Encoding source, Encoding target)
        {
            // Get source bytes
            byte[] sourceBytes = source.GetBytes(str);

            // Convert to target bytes
            byte[] targetBytes = Encoding.Convert(source, target, sourceBytes);

            // Convert target bytes to string
            char[] targetChars = new char[target.GetCharCount(targetBytes, 0, targetBytes.Length)];
            target.GetChars(targetBytes, 0, targetBytes.Length, targetChars, 0);
            return new string(targetChars);
        }

        /// <summary>
        /// Converts encoding of str from ISO-8859-1 to ISO-8859-15
        /// </summary>
        /// <param name="str">The string to convert</param>
        /// <returns>The converted string</returns>
        public static string convertEncodingFrom1To15(string str)
        {
            return convertEncoding(str, Encoding.GetEncoding("ISO-8859-1"), Encoding.GetEncoding("ISO-8859-15"));
        }
    }
}