樣本
(一).功能
當一個系統有了一定規模,可能要銷售到國外其它國家,這時候要實現多種資源檔.
本程式碼範例將介紹怎樣實現: 一個系統同時具有簡體,繁體,英文等不同資源檔.
實現原理:
將多資源檔儲存在多個*.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"); //簡體中文
}
}
}
}
(四).設定瀏覽器目前範圍資源類型
選瀏覽器中的菜單:"工具"->"選項"->“常規”選項卡->"語言",選擇語言.
選擇好後,程式就會自動讀取當前瀏覽器設定的資源檔進行顯示不同的檔案.
上面只建立了一個a.txt檔案,讀者可以根據需要分別建立多個不同的資源檔
來建立更多的資源檔
例如: Chinese.txt檔案中顯示: _name=姓名
English.txt檔案中顯示: _name=name 等,甚至可以建立任何語言資源檔