以上代碼產生的結果如下:
當以網站的方式訪問時,結果如下:
VirtualPathUtility.ToAbsolute("~/") |
= / |
HttpRuntime.AppDomainAppVirtualPath |
= / |
Request.ApplicationPath |
= / |
Page.ResolveUrl("~") |
= / |
當以虛擬目錄(http://localhost:806/web2/url.aspx)訪問時,結果如下:
VirtualPathUtility.ToAbsolute("~/") |
= /web2/ |
HttpRuntime.AppDomainAppVirtualPath |
= /web2 |
Request.ApplicationPath |
= /web2 |
Page.ResolveUrl("~") |
= /web2/ |
採用第二種和第三種方法,還需要做一下處理,因為網站訪問時是以/結尾,而以虛擬目錄訪問時則是沒有/的,進行還得進行一次判斷,稍微麻煩一點。
但是,這些方法在頁面中使用是沒有任何問題的,但是如果在 Global 的 Application_Start 事件裡需要得到網站的絕對路徑,則需要使用前面2種方法,如果使用第三種方法,則會報告如下的錯誤:
Request is not available in this context
所以,只能採取頭2種方法。例如
C# 代碼void Application_Start( object sender, EventArgs e)
{
System.IO.StreamWriter s = new System.IO.StreamWriter(HttpRuntime.AppDomainAppPath + " log.txt " );
s.WriteLine(VirtualPathUtility.ToAbsolute( " ~/ " ));
s.WriteLine(HttpRuntime.AppDomainAppVirtualPath);
s.Close();
}
1.符號“/”指程式運行所在根目錄,即IIs所在目錄。
如果iis所在目錄為:d:\programs
解決方案為d:\programs\d
網站路徑為:d:\programs\d\web\
符號“/”代表的是:d:\programs,不管你的網站前面有多少級,都應該作為一個整體。
2.符號“~/”,則是指網站所在根目錄。即d:\programs\d\web。
測試代碼如下:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(Server.MapPath("/"));
Response.Write("<br/>");
Response.Write(Server.MapPath("~/"));
}
輸出結果:
C:\inetpub\wwwroot\
D:\Programs2008\WebSite2\