App_GlobalResources和LocalResources文件夹区别

Asp.net多语言中的App_GlobalResources和LocalResources文件夹区别

App_GlobalResources的文件是全局文件资源,可以在任何页面通过Resources直接使用这里面的资源文件。示例如下:

1、在App_GlobalResources中增加一个文件叫做ResourceTest.resx

2、在ResourceTest.resx中增加两个项 PageTitle 值为“中国加油!” LabelText 值为“奥运顺利!”

3、打开aspx页面的,然后在Page_Load方法中可以直接这样使用

protected void Page_Load(object sender, EventArgs e)
       {
           this.Title = Resources.ResourceTest.PageTitle;
           Label1.Text = Resources.ResourceTest.LabelText;
       }

这里的ResouceTest就是那个资源文件的文件名,在VS中,可以自动感知出ResourceTest。

直接在页面的控件中的使用方法是:

<asp:Label ID="Label1" runat="server" Text="<%$Resources:ResourceTest,LabelText %>" ></asp:Label>

如果使用这种方式绑定了App_GlobalResources,那么就不能再绑定App_LocalResources中的资源文件了

如果要支持英文,就在App_GlobalResources中增加一个文件,文件命名格式是:ResourcesTest.en-us.resx,在页面的使用方式不变。当你用浏览器访问时,系统会自动侦测出你的浏览器设置的默认语言,然后自动调用不同的资源包来呈现出来。

除了上面所谈到的方式可以直接使用资源包,还可以通过HttpContext.GetGlobalResourcesObject来获取资源包的内容。

HttpContext.GetGlobalResourceObject(resxFile, MyResName)

HttpContext.GetGlobalResourceObject(resxFile, MyResName,CurrentCulture)这个方法第一个参数是资源文件名,第二个参数是要检索的键值。调用例子为:

string GetGlobalResources(string resxFile,string resxKey)

{

string resxValue=(string)HttpContext.GetGlobalResourceObject(resxFile, resxKey)

if(string.IsNullOrEmpty(resxValue)

{

return string.Empty;

}

return resxValue;

}

App_LocalResources文件夹,这个文件夹中放的是页面的资源文件,这些资源文件和每个Aspx页面对应。比如我在网站项目下添加了一个Default.aspx文件,在设计VS的模式下,选择工具“生成本地资源” 就会自动在App_LocalResources中生成一个名字为Default.aspx.resx的资源文件。

编程访问的方式是:

HttpContext.GetLocalResourceObject("resxFile","resxKey")

直接在控件中的访问方式:

<asp:Label ID="Label1" runat="server" meta.:resourcekey="LabelText"></asp:Label>

怎样读取App_LocalResources里某一资源文件的所有key,value值?   

public static void Main()
{
// Create a ResourceReader for the file items.resources.
ResourceReader rr = new ResourceReader("items.resources");


// Create an IDictionaryEnumerator to iterate through the resources.
IDictionaryEnumerator id = rr.GetEnumerator();

// Iterate through the resources and display the contents to the console.
while(id.MoveNext())
Console.WriteLine("\n[{0}] \t{1}", id.Key, id.Value);

rr.Close();

}  

原文地址:https://www.cnblogs.com/ajunForNet/p/2508226.html