RemarkLima
RemarkLima

Reputation: 12047

How to get the key of a resource from a localised string value?

You can get the value from a resource key with the following:

string s = Namespace.ResourceLocation.ResourceFile.KeyName;

Is there a way to get the key name from a string value?

Upvotes: 0

Views: 3149

Answers (2)

RemarkLima
RemarkLima

Reputation: 12047

For completeness, from inquisitive_mind's answer I ended up with:

var resDict = StronglyTypedResource
                   .ResourceManager
                   .GetResourceSet(CultureInfo.InvariantCulture, true, false)
                       .Cast<DictionaryEntry>()
                       .ToDictionary(x => x.Key.ToString(), x => x.Value.ToString());

To get my strongly typed resource file into a dictionary - the bit I'd missed initially was to enable createIfNotExists to load the resource file.

Then simply query the dictionary:

entity.ResourceKeyValue =
    resDict.First(x => x.Value.ToLower() == stringValue.Trim().ToLower()).Key;

Upvotes: 2

nobody
nobody

Reputation: 11090

You can iterate through the resource file and get the keyname using the value.

using System.Resources;
using (ResXResourceReader oReader = new ResXResourceReader(ResourceFilePath))
{
      IDictionaryEnumerator oResource = oReader.GetEnumerator();
      while (oResource.MoveNext())
      {
           if (oResource.Value.ToString() == "VALUE")
               return oResource.Key.ToString();
      }
 }

Upvotes: 1

Related Questions