watbywbarif
watbywbarif

Reputation: 7017

Recover from using bad code page in C#

I have read string "ńîôč˙" from file by using code page windows-1251, instead of using iso-8859-2. It should be some Cyrillic string. How to implement function that will do following in C#:

string res = Recover("ńîôč˙");

string Recover(string input)
{
    ???
}

Where res is Cyrillic string that I would have got if I used good page when reading file in first place.

Upvotes: 1

Views: 653

Answers (2)

Dirk Vollmar
Dirk Vollmar

Reputation: 176239

You can use the methods of the System.Text.Encoding class:

using System.Text;
using System;

class EncodingConverter
{
    static string ConvertEncoding(string input, 
        Encoding srcEncoding, 
        Encoding targetEncoding)
    {
        byte[] buffer = srcEncoding.GetBytes(input);
        return targetEncoding.GetString(buffer);
    }

    static void Main(string[] args)
    {
        string input = args[0];
        string converted = ConvertEncoding(input, 
            Encoding.GetEncoding("windows-1250"), 
            Encoding.GetEncoding("iso-8859-2"));
        Console.WriteLine(converted);
    }
}

Upvotes: 4

OJ.
OJ.

Reputation: 29399

Off the top of my head..

string Recover(string input)
{
   return Encoding.GetEncoding("iso-8859-2").GetString(Encoding.GetEncoding(1251).GetBytes(input));
}

Upvotes: 5

Related Questions