Converting country codes in .NET

前端 未结 10 1735
难免孤独
难免孤独 2020-12-04 23:55

In .NET is there any way to convert from three letter country codes (defined in ISO 3166-1 alpha-3) to two letter language codes (defined in ISO 3166-1 alpha-2) eg. convert

10条回答
  •  余生分开走
    2020-12-05 00:32

    To the fellow lurker: if what you want is just to derive "default" country for a given two letter language name in .NET world (for example "en" => "US", "ja" => "JP"), this does the trick

    // Can be read from CultureInfo.Name (or CultureInfo.Parent.Name if using non-generic culture)    
    var language = "ja"; // Japanese
    
    // Creates "ja-JP" culture 
    var defaultCulture = CultureInfo.CreateSpecificCulture(language);
    
    // After this, just take the split[1] (careful, check index) to get country code
    var split = defaultCulture.Name.Split('-');
    

    I've this working with a JS library that accepts only ISO3166 codes, and for 25 languages our website supports this works flawlessly. Always test your scenario

提交回复
热议问题