方案描述
本方案采用一种语言一个资源文件的方法,能够有效提高资源文件的可维护性。而VS.NET提供的一个WebForm一个资源文件的方案,无法满足统一维护的需要。
实现步骤
1. 准备资源文件
资源文件通常有.resx和.resources两种,前者是xml文件,后者是二进制文件。本方案中采用.resources作为资源文件,因此需要一个第三方提供的资源编辑器对资源文件进行编辑,我使用的是Resourcer,反正只要能编辑资源文件并且保存为.resources文件的软件都可以。在资源文件中添加一些string资源,通常情况下,只会用到string资源,有些项目可能需要全球化的图片资源,原理里一样的,本文就不涉及了。
资源文件的命名是有规定,该方案中,我把所有的资源文件名设为business.[culture].resources,其中business这个名字可以改,可以改成任何一个你喜欢的名字,[culture]部分必须使用.net允许的文化缩写,如zh-cn、ja-jp、en-us等。
2. 把资源文件放入项目
为了方便管理,我把所有的资源文件放在网站的一级目录Resources中。由于读取资源文件时要用到资源文件的物理位置,建议把Resources目录直接放在wwwroot下,否则会因为路径问题而变得很麻烦。
3. 增加默认语言设置
在web.config中加入<add key="cultureName" value="zh-cn" />,表明默认情况下使用zh-cn作为默认语言文化。
4. 通过Session设置当前语言
我们用一个Session变量——Session["cultureName"]来告诉每一个页面应该使用哪种语言进行初始化。当Session["cultureName"]==null时,表明该变量未设置过,就直接用默认语言文化,即web.config中的设置值。
如果用户想改变当前的界面语言,只需要设置Session["cultureName"]为指定的文化缩写即可。
全球化资源辅助管理类
通过这个类你不需要了解ResourceManager的使用方法,就可以完成全球化的初始化和资源读取工作。该类初始化时需要传入一个Page对象,该对象将用于获得Session变量值。一般情况下,大家只需要用该类的GetString()方法就可以了。





































































为了方便大家学习,做了个Demo给大家参考
关于Demo的一些说明:
1. 本演示在WindowsXP Professional+VS.NET2003环境下调试通过
2. 演示中提供了三种语言的资源文件:business.zh-cn.resources, business.en-us.resources,business.ja-jp.resources
它们都放在Resources目录下,每个资源文件中有001_01、001_02、001_03三个string资源,分别表示用户名、密码、生日。
3. 通过选择下拉式列表中的语言,然后按“确定”按钮,可以完成语言切换