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

7

21

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!

Idona answered 3/5, 2013 at 14:46 Comment(1)
it seems this is only achievable if the resource file ensures no duplicate values,otherwise you might get unexpected resource keys returned. i.e. if you have two Names/keys (Time_Second, Sequence_Second), both have the value of 'second'. you might get the name of 'Time_second' when you expect the other one.Holloweyed
N
29

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..

Noninterference answered 3/5, 2013 at 15:1 Comment(3)
Thanks, and what if the resource file is in assembly and not an actual (RESX) file in the project?Idona
You can specify assembly in which the resource is embeded in the ResourceManager constructor. But you still have to know resource base name. If you don't i think you could find out what resources are embeded into assembly by using Assembly.GetMainfestResourceNamesNoninterference
@jure: Is it possible to return all the key value pairs from the resource?Unpolite
C
5

you can access directly by passing key:

    public  string gtresource(string rulename)
    {
        string value = null;
        System.Resources.ResourceManager RM = new System.Resources.ResourceManager("CodedUITestProject1.Resource1", this.GetType().Assembly);
        value = RM.GetString(rulename).ToString();

        if(value !=null && value !="")
        {
            return value;

        }
        else
        {
            return "";
        }

    }
Canica answered 6/11, 2013 at 18:38 Comment(2)
On 7 lines of code, I see a couple of problems that need to be addressed: First RM.GetString(rulename) already returns a string. There's no need to call ToString(). Second, RM.GetString(rulename) can return null is the resource is not found, which will raise a NullReferenceException. Third, if(value !=null && value !="") will never be reached with a null value because of the NullReferenceException. Finally, you can replace all the if by return RM.GetString(rulename) ?? string.Empty;.Vittoria
This does not address the original question which is the "reverse" of what you are posting as solution. By a specific value they key needs to be retrieved...Glynas
C
2

Just in case it might help anyone. This ResourceHelper is inspired by jure and Mohan Singh Saini.

using System.Collections;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Threading;

public class ResourceHelper
{
    /// <summary>
    ///     ResourceHelper
    /// </summary>
    /// <param name="resourceName">i.e. "Namespace.ResourceFileName"</param>
    /// <param name="assembly">i.e. GetType().Assembly if working on the local assembly</param>
    public ResourceHelper(string resourceName, Assembly assembly)
    {
        ResourceManager = new ResourceManager(resourceName, assembly);
    }

    private ResourceManager ResourceManager { get; set; }

    public string GetResourceName(string value)
    {
        DictionaryEntry entry = ResourceManager.GetResourceSet(Thread.CurrentThread.CurrentCulture, true, true).OfType<DictionaryEntry>().FirstOrDefault(dictionaryEntry => dictionaryEntry.Value.ToString() == value);
        return entry.Key.ToString();
    }

    public string GetResourceValue(string name)
    {
        string value = ResourceManager.GetString(name);
        return !string.IsNullOrEmpty(value) ? value : null;
    }
}
Ciccia answered 3/4, 2014 at 21:0 Comment(3)
Any thoughts on how to reference strings resource in a referenced project? I keep getting an exception when attempting to reference it.Plus
I found it. For loaded RESX files you can reference the built-in resource manager. See https://mcmap.net/q/180227/-read-string-from-resx-file-in-c.Plus
@Plus Thanks for the supplement :)Ciccia
G
2

The simple and straight forward method is -

var keyValue = Resources.ResourceManager.GetString("AboutTitle");

In the above "AboutTitle" is the "KEY" part so if you have in the resource "AboutTitle= About" the above result for keyValue = About

I have used this in one of my project which is in VS2019.

Grimbly answered 22/10, 2020 at 8:14 Comment(0)
K
1
public static class ResourceManagerHelper
{
    public static string GetResourceName(this ResourceManager resourceManager, string value, CultureInfo cultureInfo, bool ignoreCase = false)
    {
        var comparisonType = ignoreCase ? System.StringComparison.OrdinalIgnoreCase : System.StringComparison.Ordinal;
        var entry = resourceManager.GetResourceSet(cultureInfo, true, true)
                                   .OfType<DictionaryEntry>()
                                   .FirstOrDefault(dictionaryEntry => dictionaryEntry.Value.ToString().Equals(value, comparisonType));

        if (entry.Key == null)
            throw new System.Exception("Key and value not found in the resource file");

        return entry.Key.ToString();
    }
}

To Call this extension method,

var key = Resources.ResourceManager.GetResourceName(value, CultureInfo.InvariantCulture, true);

In this case, we don't want to pass the resource assembly, rather we can invoke using the particular resource's resourceManager.

Kleeman answered 9/4, 2015 at 8:57 Comment(1)
ResourceManagerHelper is a common extension for ResourceManager. Every Resource file have Resource Manager, for example: Rule.resx is a resource file. Then to call Rule.ResourceManager.GetResourceName(val, mycultureinfo) Kleeman
R
0

You could use this inline code (c#, ASP.NET MVC)

var _resource = new ResourceManager(typeof(/*your resource*/));
string res = _resource.GetString(/*resource key*/);

i think this could help u.

Rest answered 22/11, 2017 at 13:34 Comment(1)
Why does this answer fix the OP's problem?Crocodile
D
0

Here is an limited example that:

  • Uses an resource files in a subfolder
  • Uses an different culture than the default one

.

public static string GetLocalizedNameReversed(string value)
{
    ResourceManager rm = new ResourceManager($"YourNamespace.YourFolder.YourResourceFileName", assembly);

    var entry = rm.GetResourceSet(new CultureInfo("nb-NO"), true, true)
            .OfType<DictionaryEntry>()
            .FirstOrDefault(e => e.Value.ToString().Equals(value, StringComparison.OrdinalIgnoreCase));

    return entry.Key.ToString();
}
Disembodied answered 11/5, 2018 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.