Getting the absolute path in ASP.NET

來源:互聯網
上載者:User

在ASP.NET中取得絕對路徑
原文:http://weblogs.asp.net/palermo4/archive/2004/05/20/135640.aspx

Typically when we create ASP.NET applications, we are developing against a virtual directory.  However, when we deploy our app to a production web server, it is likely set up as a web site.  This can have an impact on href assignments when using absolute paths.  In order for paths to be consistant between virtual directories and web sites, I created a helper method that will work in either environment.  Here is the code:

當我們建立一個ASP.NET應用程式的時候,我們都是在一個虛擬目錄下開發的。然而,當我們在虛擬機器主機(它使得
我們的網站看起來更像是一個獨立的網站,使別人不知道我們使用的虛擬目錄)上配置我們的應用程式的時候,
對於使用的絕對路徑將會在串連這裡產生一些影響。為了保證在我們的開發時用的虛擬目錄和最終的網站一致上,
我建立了一個輔助性的函數,它在兩個環境中都能很好的工作,這裡是代碼:









1: public static string GetPathFromRoot(string pathWithoutRoot)
2: {
3: string _ApplicationPath =
4: HttpContext.Current.Request.ApplicationPath;
5:
6: System.Text.StringBuilder _PathToReturn =
7: new System.Text.StringBuilder(_ApplicationPath);
8:
9: if (!pathWithoutRoot.StartsWith("/") && !_ApplicationPath.EndsWith("/"))
10: {
11: _PathToReturn.Append("/");
12: }
13:
14: _PathToReturn.Append(pathWithoutRoot);
15:
16: return _PathToReturn.ToString();
17:
18: }// GetPathFromRoot













注意:將這段代碼放到你的Global.asaxv.cs裡。
使用了HttpContext.Current.Request.ApplicationPath來獲得App的據對路徑,然後用StringBuilder類來處
理以提高效率,程式判斷了是否有'/'在最後的情況。
作者在它的修訂版本中又對pathWithoutRoot是否為null,是否length==0等情況做了判斷,豐富的函數的
廣度,我只列出了它未修訂的版本,學習主要的思路~
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.