在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等情况做了判断,丰富的函数的
广度,我只列出了它未修订的版本,学习主要的思路~