ASP.NET 2.0提供的Web Resources管理模型,很好的解决了image、css、script等外部资源的管理问题。现在只需要在solution explorer把资源文件的build action属性设为Embedded Resource。然后在assemblyinfo.cs里添加一句:


其实这个语句放任何cs文件里,保证放在最高级namespace外就行。
然后在程序中调用如下:
GetWebResourceUrl的第一个参数是用户定义的类型(这个是用来确定assembly用的),第二个参数是资源名。
上面的语句返回给browser的代码是:

当然这个WebResource.axd是不存在的,它只是IIS中的一个ISAPI影射。
使用示例代码如下:
1 #region WebResource Demo
2
3 using System;
4 using System.Collections.Generic;
5 using System.ComponentModel;
6 using System.Text;
7 using System.Web.UI;
8 using System.Web.UI.WebControls;
9
10 [assembly: WebResource("WebCtrl.cutecat.jpg", "image/jpg")]
11
12 namespace WebCtrl
13 {
14 [DefaultProperty("Text")]
15 [ToolboxData("<{0}:WebCustom runat=server>")]
16 public class WebCustom : WebControl
17 {
18 private string text;
19 private Image m_Image;
20
21 [Bindable(true)]
22 [Category("Appearance")]
23 [DefaultValue("")]
24 public string Text
25 {
26 get { return text; }
27 set { text = value; }
28 }
29
30 protected override void CreateChildControls()
31 {
32 m_Image = new Image();
33 this.Controls.Add(m_Image);
34 }
35
36 protected override void Render(HtmlTextWriter output)
37 {
38 m_Image.ImageUrl = this.Page.GetWebResourceUrl(typeof(WebCustom), "WebCtrl.cutecat.jpg");
39 this.RenderChildren(output);
40 }
41 }
42 }
43 #endregion
44
45
2
3 using System;
4 using System.Collections.Generic;
5 using System.ComponentModel;
6 using System.Text;
7 using System.Web.UI;
8 using System.Web.UI.WebControls;
9
10 [assembly: WebResource("WebCtrl.cutecat.jpg", "image/jpg")]
11
12 namespace WebCtrl
13 {
14 [DefaultProperty("Text")]
15 [ToolboxData("<{0}:WebCustom runat=server>")]
16 public class WebCustom : WebControl
17 {
18 private string text;
19 private Image m_Image;
20
21 [Bindable(true)]
22 [Category("Appearance")]
23 [DefaultValue("")]
24 public string Text
25 {
26 get { return text; }
27 set { text = value; }
28 }
29
30 protected override void CreateChildControls()
31 {
32 m_Image = new Image();
33 this.Controls.Add(m_Image);
34 }
35
36 protected override void Render(HtmlTextWriter output)
37 {
38 m_Image.ImageUrl = this.Page.GetWebResourceUrl(typeof(WebCustom), "WebCtrl.cutecat.jpg");
39 this.RenderChildren(output);
40 }
41 }
42 }
43 #endregion
44
45