网站页面(aspx.cs)读取资源文件(*.resx)对应键值的value值

.NET里可以用资源文件实现软件系统多语言版本,今天添加了一个资源文件,然后在网页里面动态调用,
由于以前没接触过这方面的知识,所以不太清楚怎么样加裁一个资源文件,来实现动态调用!然后就是GOOGLE搜索,发现大部分都是用如下模式:
   1、System.Resources.ResourceManager manager = new System.Resources.ResourceManager("资源文件名", Assembly.GetExecutingAssembly());
      调试了好长时间后来才发现“资源文件名” 这个变量只适合“*.resources”为后缀的资源文件,
   2、Properties.Resource这种方式来加载,后面发现在页面下的cs类里面根本就没有Properties这个类(在windows应用程序下才能这个属性方法),又行不通

后面通过VS2008 MSDN上发现了一种读取resx资源文件的方法,自己整理了一下把代码贴上来了,希望对大家能有所帮助:

using System.Resources;
using System.Collections;

/// <summary>
/// 根据键值获取对应资源文件的value值
/// </summary>
/// <param name="resxFileName">资源文件路径</param>
/// <param name="sKey">key名称</param>
/// <returns>string</returns>
public static string GetResxValue(string resxFileName, string sKey)
{
    string valueResult = "";

    if (System.IO.File.Exists(resxFileName))    //For Example:string filePaht=Server.MapPath("App_LocalResources/Default.aspx.resx")
    {
        ResXResourceReader aa = new ResXResourceReader(resxFileName);
        foreach (DictionaryEntry d in aa)
        {
            if (d.Key.ToString() == sKey)
            {
                valueResult = d.Value.ToString();
            }
        }
    }

    return valueResult;
}

补充一:
不过今天又发现了两个更简单的读取资源文件的方法(VS自带的)

GetGlobalResourceObject (String Param1, String Param2):读取全局资源文件的方法
参数说明:Param1(资源文件类名:即资源文件名,不带resx)
          Param2(键值名)

GetLocalResourceObject(string Parma1):读取本地资源文件方法
参数说明:Param1(键值名)

充二:
读取全局资源文件内容,但发布之后这个文件实际不存在会报错
using System.Resources;
……
 string fileName = Server.MapPath(@"App_GlobalResources\LogResource.resx");
        ResXResourceReader reader = new ResXResourceReader(fileName);
        IDictionaryEnumerator enumerator = reader.GetEnumerator();
        while (enumerator.MoveNext())
        {
            string key = (string)enumerator.Key;
            object obj2 = enumerator.Value;
            Response.Write("key值:"+key);
            Response.Write("内容值:" + obj2 + "<br>");
        }

补充三:
针对全局资源文件App_GlobalResources发布后变成App_GlobalResources.dll,读取其资源内容集合解决方案
System.Reflection.Assembly ass = System.Reflection.Assembly.Load("App_GlobalResources");
Type type = ass.GetType("Resources." + "LogResource");
System.Reflection.PropertyInfo[] pa = type.GetProperties();
string strC="";
foreach (System.Reflection.PropertyInfo tmpP in pa)
{
    //键名
    strC+ = tmpP.Name.Trim();
   
    //键值
    if(tmpP.GetValue(null, null)!=null)
  strC+ = tmpP.GetValue(null, null).ToString();
}

Response.Write(strC);

原文地址:https://www.cnblogs.com/scgw/p/2030225.html