Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Culture Display Name in its language

Tags:

c#

.net

asp.net

I am getting the current culture as follows:

var culture = Thread.CurrentThread.CurrentCulture.DisplayName;

The problem is that I always get the name in English:

  • EN becomes English
  • PT becomes Portuguese instead of Português
  • FR becomes French instead of ...

How can I get the DisplayName of a Culture in that specific language?

Thank You, Miguel

like image 973
Miguel Moura Avatar asked Oct 21 '13 13:10

Miguel Moura


2 Answers

If one just tries to get the localized language of a culture (without the country) one can use this snippet:

CultureInfo culture = Thread.CurrentThread.CurrentCulture;

string nativeName = culture.IsNeutralCulture
    ? culture.NativeName
    : culture.Parent.NativeName;

If one will use a specific localized language name, one can use this:

string language = "es-ES";
CultureInfo culture = new CultureInfo(language);

string nativeName = culture.IsNeutralCulture
    ? culture.NativeName
    : culture.Parent.NativeName;

If one wants to have a title case name (e.g. Français instead of français), use this line:

string result = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(nativeName);

As a method:

private static string GetTitleCaseNativeLanguage(string language)
{
    CultureInfo culture = new CultureInfo(language);

    string nativeName = culture.IsNeutralCulture
        ? culture.NativeName
        : culture.Parent.NativeName;

    return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(nativeName);
}

Or as an extension method:

public static string GetNativeLanguageName(this CultureInfo culture, bool useTitleCase = true)
{
    string nativeName = culture.IsNeutralCulture
        ? culture.NativeName
        : culture.Parent.NativeName;

    return useTitleCase
        ? CultureInfo.CurrentCulture.TextInfo.ToTitleCase(nativeName)
        : nativeName;
}
like image 130
Baccata Avatar answered Sep 27 '22 21:09

Baccata


A search on cultureinfo.Displayname led to nativename on msdn, and that led to How to translate CultureInfo language names

like image 38
oerkelens Avatar answered Sep 27 '22 22:09

oerkelens