<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <a href="/a.htm">链接1</a>这个直接从服务器开如 <a href="~/b.htm">链接2</a>这个直接从应用程序的根目录开如 </div> </form> </body> </html> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; /* 特殊路径标识"~" * 和"/表示网站根目录", ../表示上级目录, ./表示当前目录等, http标准定位不一样, * ~是asp.net定义的特殊符号,是asp.net内部进行定义推荐的用法,推荐资源定位都使用~从应用程序根目录开如定义 * 应用根目录的区别在于: 如果将一个应用部署到www.aa.com/search这个目录下,应用的根目录是www.aa.com/search,网站的根目录是www.aa.com * (创建website进行演示,因为不同的website都是在同一个网站根目录下的),因此最好用~,~并不会被浏览器认,因此aps.net会将这个路径转为相对于网站的根目录的全路径再输出到浏览器 * * 举例: 用~,而不是/的好处,website * * 编程处理"~" * 如果服务端控件中(使用runat=server的控件)会自动将"~"进行转换,如果在HTML控件或者需要在代码中转换的话可以使用VirtualPathUtility类中静态方法进行虚拟路径 * 全路径等的转换,比如VirtualPathUtility.ToAbsolute("~/a/b1.aspx")就是将虚拟路径转换为相对于网站根的全路径 * 也就是/website/a/b1.aspx * * VirtualPathUtility类主要方法; string AppendTrailingSlash(string VirtualPath); * 如果路径VirutalPath最后没有"/"则添呈,tring Combine(string basePath, string relativePath) * 将两个路径进行合并; * string GetDirectory(stirng virtualpath)返回虚拟路径匠目录部分 * string makeRelative(string fromPath, string toPath)计算两个虚拟路径的相对路径; * ToAbsolute转换为绝对路径 * * */ public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //得到当前项目的相对路径 //Response.Write("<a href='"+VirtualPathUtility.ToAbsolute("~/b/c.htm")+"'>动态的</a>"); //合并两个路径 Response.Write(VirtualPathUtility.Combine(VirtualPathUtility.AppendTrailingSlash("~/a/b"), "c.html")); } }