Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net Get all Resources from .resx Without Specifying Culture (ResourceManager.GetResourceSet )

I first came across a question similar to mine here at stack overflow: Loop through all Resources in ResourceManager - C#. It only solved part of what I need to do. When you request an entry in a resource file for a specific culture, if there is not one present it will default back on the neutral culture resource file.

I need to loop through each entry for a given resource file and GetResourceSet requires a culture. For example I have a neutral resource file with 3 entries in it and a culture specific resource file accompanying the neutral file with 1 entry.

My neutral resource example file is MyResource.resx and my culture specific resource example file is MyResource.en-gb.resx. The following code shows how I am currently trying to loop through and access all of the resource entries.

Dim cultInfo as New CultureInfo(culture)
For Each entry As System.Collections.DictionaryEntry In myResourceManager.GetResourceSet(cultInfo, True, True)

Next

Neutral Resource File Entries

  • FullName / Full Name
  • PhoneNumber / Phone Number
  • State / State

Culture Specific Resource File Entry

  • State / County

When I call GetResourceSet for the specific culture I only get back 1 entry. I was expecting (and want) to get back all 3 entries with the one culture specific entry overridden. Here is what I want returned:

  • FullName / Full Name
  • PhoneNumber / Phone Number
  • State / County

Is there anyway that I can do this? Thanks.

like image 280
Jason Avatar asked Apr 25 '11 21:04

Jason


1 Answers

The GetString method of a ResourceManager object properly handles the traversing of resource files to locate the correct Value for a given key based on a culture. The base/neutral/default resource file can be obtained using the CultureInfo.InvariantCulture, which gives you all the possible keys for the resource file (assuming you setup your resource files this way).

Looping on the DictionaryEntry objects found in the GetResourceSet method of a ResourceManager, based on the Invariant Culture and then calling GetString for each Key using the specific culture passed in, you will get the correct Value for a given key based on the culture.

For Each entry As DictionaryEntry In myResourceManager.GetResourceSet(CultureInfo.InvariantCulture, True, True)
     Dim strKey as String = entry.Key.ToString()
     Dim strValue as String = myResourceManager.GetString(entry.Key.ToString(), cultInfo)
Next

Hope this helps!

like image 176
Jason Avatar answered Sep 18 '22 23:09

Jason