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

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

|root
 |pic
 |web
 |usercontrol

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

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

public static string GetApplicationPath(HttpRequest request) 
        
{
            
string path = string.Empty;
            
try 
            
{
                
if(request.ApplicationPath != "/")
                    path 
= request.ApplicationPath;
            }

            
catch (Exception e)
            
{
                
throw e;
            }

            
return path;
        }


在需要的地方进行调用,例如:
<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.
 
在基类定义下面的属性

protected string appPath
        
{
            
get
            
{
                
string path=String.Empty;
                
try
                
{
                    
if ("/"!=Request.ApplicationPath)
                    
{
                        path
=Request.ApplicationPath;
                    }

                }

                
catch(Exception e)
                
{
                    
throw e;
                }

                
return path;    
            }

        }


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

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

<asp:Image id="Image1" runat="server" ImageUrl="../pic/register.gif"></asp:Image>

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

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

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


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


posted @ 2005-01-24 17:34  aierong  阅读(1320)  评论(1编辑  收藏  举报