在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等情況做了判斷,豐富的函數的
廣度,我只列出了它未修訂的版本,學習主要的思路~