views:

273

answers:

2

Hi,

I have a WinForms application which can be localized through satellite assemblies for the resx-files. The user can switch the application language at runtime.

So my question is: Is there any way to dynamically find out which cultures are shipped as localized resources with my client?

A: 

The easiest way we found was to look at the satellite assembly files and work it out from their parent directory names, which use the standard "en-US" style names.

Jeff Yates
+2  A: 

Here's the code that I use. It searches satellite assemblies in the program's subdirectories

    private static ReadOnlyCollection<CultureInfo> GetAvailableCultures()
    {
        List<CultureInfo> list = new List<CultureInfo>();

        string startupDir = Application.StartupPath;
        Assembly asm = Assembly.GetEntryAssembly();

        CultureInfo neutralCulture = CultureInfo.InvariantCulture;
        if (asm != null)
        {
            NeutralResourcesLanguageAttribute attr = Attribute.GetCustomAttribute(asm, typeof(NeutralResourcesLanguageAttribute)) as NeutralResourcesLanguageAttribute;
            if (attr != null)
                neutralCulture = CultureInfo.GetCultureInfo(attr.CultureName);
        }
        list.Add(neutralCulture);

        if (asm != null)
        {
            string baseName = asm.GetName().Name;
            foreach (string dir in Directory.GetDirectories(startupDir))
            {
                // Check that the directory name is a valid culture
                DirectoryInfo dirinfo = new DirectoryInfo(dir);
                CultureInfo tCulture = null;
                try
                {
                    tCulture = CultureInfo.GetCultureInfo(dirinfo.Name);
                }
                // Not a valid culture : skip that directory
                catch (ArgumentException)
                {
                    continue;
                }

                // Check that the directory contains satellite assemblies
                if (dirinfo.GetFiles(baseName + ".resources.dll").Length > 0)
                {
                    list.Add(tCulture);
                }

            }
        }
        return list.AsReadOnly();
    }
Thomas Levesque