日期:2010-05-29  浏览次数:20448 次

(一).功能
  当一个系统有了一定规模,可能要销售到国外其它国家,这时候要实现多种资源文件.
  本代码示例将介绍怎样实现: 一个系统同时具有简体,繁体,英文等不同资源文件.
  实现原理:
  将多资源文件存储在多个*.txt文件(例如CN.txt En.txt等)中,程序根据当前当前浏览器
  语言设置 读取相应的资源文件
(二).具体步骤如下
  1. 创建一个资源文件
     a.建立一个记事本文件: a.txt,并在里面写入:  _name=姓名 
     b.选"文件"->"另存为"->在弹出窗口最下面的"编码"格式栏选择需要保存的格式:
        Unicode 或 Unicode big endian 或 UIF-8,
       不要选择ANSI编码格式(否则,读取的时候会检索不到资源,我实验的时候输出了一个:"?")
  2. 编译资源文件
     打开Dos窗口运行命令:
       C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin\resgen                     C:\Inetpub\wwwroot\多种资源文件\Resource\a.txt
     注意一点: 路径要修改为您自己的文件实际路径
     运行后会在a.txt的当前文件夹下面生成一个资源文件:  a.resources
     系统在运行时就是动态读取a.resources文件来显示不同资源文件的,就像我们在编程时
     写的代码为*.cs文件,计算机只认识*.cs编译后的*.aspx.resx一样    
(三).代码
  经过(二)步骤之后,就可以运行代码了.
  主要操作资源文件类代码如下:
 
  using System;
using System.Resources;
using System.Globalization;

namespace 多种资源文件
{
 /// <summary>
 /// Class1 的摘要说明。
 /// </summary>
 class ResourceClass
 {
  /// <summary>界面资源对象</summary>
  public ResourceManager  myResManager;

  /// <summary>界面区域对象对象</summary>
  protected CultureInfo myCulture;

  protected string strPath = @"C:\Inetpub\wwwroot\多种资源文件\Resource";  //这里要修改成自己的实际路径

  public string strLangString = "zh-CN";

  public ResourceClass()
  {  
   
   // 建立資源管理器实例
   this.myResManager = ResourceManager.CreateFileBasedResourceManager("a",this.strPath,null);
   
   // 建立区域实例
   this.myCulture = new CultureInfo(this.strLangString);
  }
  public string GetResource(string strKey)
  {
   string strValue = "";
   strValue = myResManager.GetString(strKey,myCulture);
   return strValue;
  }
  public static string GetBrowserDefaultLanguage(string strLangString)  // "zh-cn,zh-tw;q=0.5"
  {
   try
   {
    int[] intLang = new int[3];

    intLang[0] = strLangString.IndexOf("zh-tw");
    intLang[1] = strLangString.IndexOf("zh-cn");
    intLang[2] = strLangString.IndexOf("en");

    int intMin = 0;

    if(intLang[0] != -1 && intLang[1] != -1){intMin = Math.Min(intLang[0],intLang[1]);}
    if(intLang[2] != -1){intMin = Math.Min(intMin,intLang[2]);}

    if(intMin == intLang[0])  // 繁体中文.
    {
     return ("zh-TW");
    }
    else if(intMin == intLang[1])  // 简体中文.
    {
     return ("zh-CN");
    }
    else        // 英文.
    {
     return ( "en");
    }
   }
   catch
   {
    return ( "zh-CN");