Get RegionInfo by country name?

前端 未结 6 1631
一个人的身影
一个人的身影 2020-12-18 22:52

I want to be able to get RegionInfo by doing the following:

new RegionInfo(\"United Kingdom\");

but this throws an exception a

相关标签:
6条回答
  • 2020-12-18 23:18

    That same page you linked also says:

    The RegionInfo name is one of the two-letter codes defined in ISO 3166 for country/region. Case is not significant; however, the Name, the TwoLetterISORegionName, and the ThreeLetterISORegionName properties return the appropriate code in uppercase.

    The codes are on the page, and GB appears to be the 2 letter code for the UK (it's in code order to be difficult searching!). So try this:

    new RegionInfo("GB");
    

    Or if you're using .NET 2.0+, it's recommended you use the full culture name:

    new RegionInfo("en-GB");
    
    0 讨论(0)
  • 2020-12-18 23:21

    Look at the MSDN page:

    A string containing one of the two-letter codes defined in ISO 3166 for country/region.

    You need the ISO 3166 code for the UK, not the name of the country.

    Here's the code you need.

    0 讨论(0)
  • 2020-12-18 23:26

    If I navigate to the constructor the summary I see in Visual Studio says:

    name: A string that contains a two-letter code defined in ISO 3166 for country/region.-or-A string that contains the culture name for a specific culture, custom culture, or Windows-only culture. If the culture name is not in RFC 4646 format, your application should specify the entire culture name instead of just the country/region.

    The entire culture name would be 'en-GB'.

    Or you could use 'GB'

    0 讨论(0)
  • 2020-12-18 23:38

    Note this comment from the metadata for the parameter name which explains the change from .NET Framework 2.0 on:

        //     A string containing one of the two-letter codes defined in ISO 3166 for country/region.-or-Beginning
        //     in .NET Framework version 2.0, a string containing the culture name for a
        //     specific culture, custom culture, or Windows-only culture. If the culture
        //     name is not in RFC 4646 format, your application should specify the entire
        //     culture name, not just the country/region.
    
    0 讨论(0)
  • 2020-12-18 23:41
      var regions = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(x => new RegionInfo(x.LCID));
      var englishRegion = regions.FirstOrDefault(region => region.EnglishName.Contains(name));
    

    If you want to get RegionInfo by the country name, you could get an IEnumerable<RegionInfo> and then filter based on the EnglishName as above. This gives you the ability to populate things such as comboboxes too.

    0 讨论(0)
  • 2020-12-18 23:45

    From MSDN;

    A string that contains a two-letter code defined in ISO 3166 for country/region.

    UNITED KINGDOM looks ok on Country names and code elements on the ISO website.

    GB UNITED KINGDOM

    Try with;

    new RegionInfo("GB");
    
    0 讨论(0)
提交回复
热议问题