How to get Name by string Value from a .NET resource (RESX) file

Learner picture Learner · May 3, 2013 · Viewed 50.2k times · Source

Here's how my RESX file look like:

Name            Value        Comments
Rule_seconds    seconds      seconds
Rule_Sound      Sound        Sound

What I want is: Name by string Value, something like below:

public string GetResxNameByValue(string value)
{
// some code to get name value
}

And implement it like below:

string str = GetResxNameByValue("seconds");

so that str will return Rule_seconds

Thanks!

Answer

Jurica Smircic picture Jurica Smircic · May 3, 2013

This could work

private string GetResxNameByValue(string value)
    {
            System.Resources.ResourceManager rm = new System.Resources.ResourceManager("YourNamespace.YourResxFileName", this.GetType().Assembly);


        var entry=
            rm.GetResourceSet(System.Threading.Thread.CurrentThread.CurrentCulture, true, true)
              .OfType<DictionaryEntry>()
              .FirstOrDefault(e => e.Value.ToString() ==value);

        var key = entry.Key.ToString();
        return key;

    }

With some additional error checking..