从本地.resx文件获取值

时间:2011-01-19 09:25:47

标签: asp.net

如何从asp.net中的本地.resx文件中获取价值?

2 个答案:

答案 0 :(得分:5)

来自代码隐藏:

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);

如果您需要在页面/用户控件上直接填充值,则可以使用these techniques之一从资源文件中获取值。

答案 1 :(得分:0)

您可以使用此方法从资源文件中读取。您可以在配置中保留文件路径或使其成为常量,并将其从方法中删除。您也可以将其作为一种静态方法,以便更好地练习。

/// <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;
}