Framework Tips II: How to get default ANSI Encoding for given culture

It’s sometimes useful to know what is the default ANSI CodePage, for some given culture. It’s quite easy to achieve, thanks to System.Globalization namespace.

CultureInfo cultureInfo = CultureInfo.GetCultureInfo(1252);

Encoding encoding = Encoding.GetEncoding(cultureInfo.TextInfo.ANSICodePage);

However this code will not always work correctly. The problem is, not every culture has default ANSI CodePage, and therefore, for them you’d have to have plan B, like using UTF-8.

CultureInfo cultureInfo = CultureInfo.CurrentUICulture;

int codePage = cultureInfo.TextInfo.ANSICodePage;

Encoding encoding = codePage.Equals(0)?

                        Encoding.UTF8:

                        Encoding.GetEncoding(codePage);

To see, all such cultures, you can use following code:

var cultures = from c in CultureInfo.GetCultures(CultureTypes.AllCultures)

                         where c.TextInfo.ANSICodePage.Equals(0)

                         select c;

foreach (CultureInfo info in cultures)

    Console.WriteLine("{0,-10}{1}", info.Name, info.EnglishName);

4 Thoughts.

  1. Thanks a lot brother. You saved my day, may God save your all days.
    If everyone was as gracious as you, the world would be a much better place to live! 🙂

  2. I think you inverted two commands. This looks better:

    Encoding encoding = codePage.Equals(0)?Encoding.UTF8:Encoding.GetEncoding(codePage);

Comments are closed.