asp.net中的幾個路徑問題!

來源:互聯網
上載者:User

以上代碼產生的結果如下:
當以網站的方式訪問時,結果如下: 

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\

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.