Search code examples
c#localizationresource-files

How to get the value of a Resource from it's string name


I have been using resource files and referencing them in my views in the standard way for example Resources.Labels.CountryName. But I have a situation where I need to get the value of the resource in my C# from the resource name as a string i.e.

string resourceName = "Resource.Labels.CountryName";

How would I get the value in the resource file from this string?


Solution

  • Normally you get resources with

    GetLocalResourceObject("~/VirtualPath", "ResourceKey");
    GetGlobalResourceObject("ClassName", "ResourceKey");
    

    You may adapt this. I write my own extensions for the HTML helper like this one for global resources:

    public static string GetGlobalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey)
    {
        var resource = htmlHelper.ViewContext.HttpContext.GetGlobalResourceObject(classKey, resourceKey);
        return resource != null ? resource.ToString() : string.Empty;
    }
    

    I think, in your example with this you would get the resource in your view with @Html.GetGlobalResource("Labels", "CountryName").

    Because local resources need the virtual path and I don't want to write it into the view, I use this combination, which gives both opportunities:

    public static string GetLocalResource(this HtmlHelper htmlHelper, string virtualPath, string resourceKey)
    {
        var resource = htmlHelper.ViewContext.HttpContext.GetLocalResourceObject(virtualPath, resourceKey);
        return resource != null ? resource.ToString() : string.Empty;
    }
    
    public static string Resource(this HtmlHelper htmlHelper, string resourceKey)
    {
        var virtualPath = ((WebViewPage) htmlHelper.ViewDataContainer).VirtualPath;
        return GetLocalResource(htmlHelper, virtualPath, resourceKey);
    }
    

    With that you can get a local resource very comfortable by writing @Html.Resource("Key") in your view. Or use the first method to get local resources of other views like with @Html.GetLocalResource("~/Views/Home/AnotherView.cshtml", "Key").