3

I have a MVC website which is using .resx files for localization. However, the current behavior for determining which localizations are supported requires iterating over the physical .resx files, and they don't exist once the site has been compiled for publishing.

The folder structure is currently:

  • Language Resources
    • Resource.en-US.resx
    • Resource.fr-CA.resx
    • Resource.hi.resx
    • Resource.resx

Trying to get the list of all the resource files via GetManifestResourceNames(), as per this answer, only produces the single LanguageResources.Resource.resources file that represents the master, unlocalized list. It may or may not have the localizations embedded into it, but there's no way I've found to see that.

How can I tell at runtime that I support three languages?

The end goal is to build a dropdown based on these three values. If there's another way I should be approaching this problem, answers which address that are also acceptable.

Community
  • 1
  • 1
Bobson
  • 13,498
  • 5
  • 55
  • 80

1 Answers1

0

Following the sidebar links for my question, I eventually found this question, and Hans Holzbart's excellent answer, which I'm reproducing below. The question itself is approaching it from a different direction, but the answer is equally applicable to my situation.

// Pass the class name of your resources as a parameter e.g. MyResources for MyResources.resx
ResourceManager rm = new ResourceManager(typeof(MyResources));

CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
foreach (CultureInfo culture in cultures)
{
    try
    {
        ResourceSet rs = rm.GetResourceSet(culture, true, false);
        // or ResourceSet rs = rm.GetResourceSet(new CultureInfo(culture.TwoLetterISOLanguageName), true, false);
        string isSupported = (rs == null) ? " is not supported" : " is supported";
        Console.WriteLine(culture + isSupported);
    }
    catch (CultureNotFoundException exc)
    {
        Console.WriteLine(culture + " is not available on the machine or is an invalid culture identifier.");
    }
}

For my purposes, I had to filter out the Invariant culture with .Where(x => x.Name != ""), but other than that, this worked great.

Community
  • 1
  • 1
Bobson
  • 13,498
  • 5
  • 55
  • 80