Get Value from local .resx file [closed]

2020-03-30 05:10发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 7 years ago.

How can i get value from local .resx file in asp.net?

回答1:

From code-behind:

CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");

// Gets the value of associated with key "MyKey" from the local resource file for a given culture ("~/MyPage.aspx.en.resx") or from the default one ("~/MyPage.aspx.resx")
object keyValue = HttpContext.GetLocalResourceObject("~/MyPage.aspx", "MyKey", culture);

If you need the value to be populated directly on your page/user control then you can use one of these techniques to get the values from the resource files.



回答2:

You can use this method to read from your resource file. You can keep the file path in your config or make it a constant and remove it from your method. You can also make it a static method for better practice.

/// <summary>
/// method for reading a value from a resource file
/// (.resx file)
/// </summary>
/// <param name="file">file to read from</param>
/// <param name="key">key to get the value for</param>
/// <returns>a string value</returns>
public string ReadResourceValue(string file, string key)
{
    //value for our return value
    string resourceValue = string.Empty;
    try
    {
        // specify your resource file name 
        string resourceFile = file;
        // get the path of your file
        string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
        // create a resource manager for reading from
        //the resx file
        ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
        // retrieve the value of the specified key
        resourceValue = resourceManager.GetString(key);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        resourceValue = string.Empty;
    }
    return resourceValue;
}