資源檔的使用真是挺繁的,但是會用了以後就很簡單了。
到CSDN搜尋一下,裡面有一篇文章,介紹了資源檔的建立和使用,一開始沒有弄清楚,
原來是這麼回事。
首先,你必須把要使用的資源檔編譯到資源檔中,這個資源檔是控制台應用程式產生的,不是添加的name.resx檔案。
using System ;
using System.Drawing ;
using System.Resources ;
namespace Resources
{
/// <summary>
/// Class1 的摘要說明。
/// </summary>
class Class1
{
/// <summary>
/// 應用程式的主進入點。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此處添加代碼以啟動應用程式
//
ResourceWriter rw = new ResourceWriter ( "Image.resources" ) ;
Image canceloff = Image.FromFile (@"E:\源碼\myWebControl\myWebControl\IMG\link.gif") ;
Image canceloff1 = Image.FromFile (@"E:\源碼\myWebControl\myWebControl\IMG\haozhan.gif") ;
Image canceloff2 = Image.FromFile (@"E:\源碼\myWebControl\myWebControl\IMG\ejobshow.gif") ;
rw.AddResource ( "link.gif" , canceloff ) ;
rw.AddResource ( "haozhan.gif" , canceloff1 ) ;
rw.AddResource ( "ejobshow.gif" , canceloff2 ) ;
rw.Generate ( ) ;
rw.Close ( ) ;
}
}
}
把上面的程式編譯,執行exe檔案後就得到了Image.resources檔案,你可以開啟看看,裡面都是二進位代碼。
把這個Image.resources添加到你要使用這些圖片的工程中,確定加入以後檔案Image.resources屬性的“產生操作”是“內嵌資源”,
然後就可以使用了,在需要使用的地方添加以下的代碼:
ResourceManager rm=new ResourceManager("myWebControl.Image",Assembly.GetExecutingAssembly());
System.Drawing.Image img1=(System.Drawing.Image)rm.GetObject("link.gif");
注意:new ResourceManager的參數"myWebControl.Image" 有點麻煩:
myWebControl是你當前程式的命名空間(這裡不是產生這個資源檔的命名空間,我沒有注意,這裡搞了好一會,沒有理解好),Image是資源檔名,
特別要注意的是,一定要把命名空間寫上,不然會有錯誤,這個也花了好長時間,因為msdn裡面沒有清楚講解這個參數怎麼寫,一般都直接寫個Image,所以有錯誤:
System.Resources.MissingManifestResourceException: 未能在給定的程式集中找到任何適合於指定的地區性(或非特定地區性)的資源。請確保已將“Image.resources”正確嵌入或連結到程式集“myWebControl”。 baseName: Image locationInfo: <null> resource file name: Image.resources assembly: myWebControl, Version=2.0.0.2, Culture=neutral, PublicKeyToken=null
你看這個錯誤提示:請確保已將“Image.resources”正確嵌入或連結到程式集“myWebControl”。
好象告訴你沒有把“Image.resources”加入工程一樣,但是你的確加了,根本不知道怎麼回事,就是因為你沒有寫命名空間或者命名空間寫錯誤了。