在开发中我们为了整个程序目录结构清晰化,望望会建立许多不同的文件目录.
例如结构如下:

|root
 |pic
 |web
 |usercontrol

在web目录中,我们怎么取到pic目录中的图片路径呢?

方法1:
让我们先看看ASP.NET StartKit TimeTracker的解决方案:
ASP.NET StartKit TimeTracker的类Global中定义了一个公有方法:

代码阅读总结之ASP.NET StartKit TimeTracker(应用程序路径之处理笔记)public static string GetApplicationPath(HttpRequest request) 
        }


在需要的地方进行调用,例如:
<a href='<%= Global.GetApplicationPath(Request) %>/<%# ((ASPNET.StarterKit.TimeTracker.BusinessLogicLayer.TabItem)

Container.DataItem).Path %>'>
      <%# ((ASPNET.StarterKit.TimeTracker.BusinessLogicLayer.TabItem) Container.DataItem).Name %>
</a>

我对此方法进行了修改:

我先定义一个页面基类.
public class PageBase :System.Web.UI.Page
让系统中的其他aspx页面继承PageBase.
 
在基类定义下面的属性

代码阅读总结之ASP.NET StartKit TimeTracker(应用程序路径之处理笔记)protected string appPath
        }


在我的aspx页中,进行下面属性绑定得到图片
<img src='<%= appPath+"/pic/register.gif" %>' >

方法2:
也是我以前常用的方法

<asp:Image ></asp:Image>

其实服务器控件支持另一种路径表示方法:"~", 相当于HttpRequest.ApplicationPath
<asp:Image Runat="server" ></asp:Image>

非服务器控件也可以这样:
<img  src="../pic/register.gif">

方法3:
用户的机器上部署的时候,将路径保存在web.config里面了。然后图片的路径是在后台的.cs中用Configuration.appsettings确定
这方法是最差的一招


总结:个人感觉方法1最好,最灵活,也是我在许多微软例题中看到的用得最多的方法。
不知道还有没有其他方法,欢迎指点。


相关文章:

  • 2022-02-24
  • 2021-09-23
  • 2021-06-01
  • 2021-11-25
  • 2021-11-06
猜你喜欢
  • 2021-11-27
  • 2021-10-14
  • 2021-10-01
  • 2021-12-29
  • 2022-01-15
  • 2021-05-06
  • 2021-09-22
相关资源
相似解决方案