ASP.NET 中使用資源檔

來源:互聯網
上載者:User

在 Visual Web Developer 2005 Express Edition 中可以建立資源檔(Resource File),我們可以向其中存入字串、圖片、表徵圖、文字檔等內容,並且可以在 ASP.NET 中使用資源檔。

資源檔的副檔名是 .resx,在表單軟體中,可以利用 ResXResourceReader 來直接讀取 .resx 檔案。但是在 ASP.NET 中,我們不能這樣做,我們需要利用 ResGen.exe 將 .resx 產生二進位的 .resources(注意副檔名)檔案,然後利用 ResourceReader 來讀取。注意是 ResXResourceReader 和 ResourceReader。

建立 .resx

在 Visual Web Developer 2005 Express Edition 建立 .resx 檔案非常簡單,可以在“建立檔案”對話方塊中選擇該類型的檔案,不用多述,當然也可以利用 ResourceWriter 來建立。

產生 .resources

我們需要安裝 .NET Framework,然後可以在類似 C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin 的位置找到 ResGen.exe 這個工具,利用這個工具將 .resx 檔案編譯成 .resources 檔案。

ResGen E:\Resource1.resx E:\Resource1.resources

讀取 .resources

利用 ResourceReader。

ResourceReader 的名稱空間是:

System.Resources

樣本

ResourceReader reader = new ResourceReader(Server.MapPath("Resource1.resources"));

string resourceType;
byte[] resourceData;
reader.GetResourceData("String1", out resourceType, out resourceData);
byte[] arr = new byte[resourceData.Length-1];
for (int i = 0; i < arr.Length; i++)
{
    arr[i] = resourceData[i + 1];
}
lb.Text = Encoding.UTF8.GetString(arr);

System.Collections.IDictionaryEnumerator en = reader.GetEnumerator();
while (en.MoveNext())
{
    lb.Text += "<br />" + en.Value.ToString();
}

reader.Close();

範例程式碼包含四段,第一段為建立 ResourceReader,第四段為釋放 ResourceReader 資源。關於 Close 釋放資源,請參見 Finalize(解構函式)、Dispose、Close 的區別與使用。

第二、三段為兩種讀取方式。

GetResourceData 第一個參數 resourceName 大小寫敏感, Encoding.UTF8.GetString 將 byte 數組轉化成字串。我不知道為什麼 GetResourceData 讀取出的 byte 總是多一個位元組,所以利用數組轉化去掉前面的一個位元組。

第三段中利用 GetEnumerator 取出所有的資源,再分別顯示出來。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.