将Web站点下的绝对路径转换为虚拟路径
点击次数:19 次 发布日期:2008-11-26 12:43:49 作者:源代码网
|
源代码网推荐 将Web站点下的绝对路径转换为相对于指定页面的虚拟路径 源代码网推荐 /**//// <summary> 源代码网推荐 /// 将Web站点下的绝对路径转换为相对于指定页面的虚拟路径 源代码网推荐 /// </summary> 源代码网推荐 /// <param name="page">当前页面指针,一般为this</param> 源代码网推荐 /// <param name="specifiedPath">绝对路径</param> 源代码网推荐 /// <returns>虚拟路径, 型如: ../../</returns> 源代码网推荐 public static string ConvertSpecifiedPathToRelativePathForPage(Page page, string specifiedPath) 源代码网推荐 { 源代码网推荐 // 根目录虚拟路径 源代码网推荐 string virtualPath = page.Request.ApplicationPath; 源代码网推荐 // 根目录绝对路径 源代码网推荐 string pathRooted = HostingEnvironment.MapPath(virtualPath); 源代码网推荐 // 页面虚拟路径 源代码网推荐 string pageVirtualPath = page.Request.Path; 源代码网推荐 源代码网推荐 if (!Path.IsPathRooted(specifiedPath) || specifiedPath.IndexOf(pathRooted) == -1) 源代码网推荐 { 源代码网推荐 throw new Exception(string.Format(""{0}"是虚拟路径而不是绝对路径!", specifiedPath)); 源代码网推荐 } 源代码网推荐 源代码网推荐 // 转换成相对路径 源代码网推荐 //(测试发现,pathRooted 在 VS2005 自带的服务器跟在IIS下根目录或者虚拟目录运行似乎不一样, 源代码网推荐 // 有此地方后面会加"", 有些则不会, 为保险起见判断一下) 源代码网推荐 if (pathRooted.Substring(pathRooted.Length - 1, 1) == "\") 源代码网推荐 { 源代码网推荐 specifiedPath = specifiedPath.Replace(pathRooted, "/"); 源代码网推荐 } 源代码网推荐 else 源代码网推荐 { 源代码网推荐 specifiedPath = specifiedPath.Replace(pathRooted, ""); 源代码网推荐 } 源代码网推荐 源代码网推荐 string relativePath = specifiedPath.Replace("\", "/"); 源代码网推荐 源代码网推荐 string[] pageNodes = pageVirtualPath.Split("/"); 源代码网推荐 源代码网推荐 // 减去最后一个页面和前面一个 "" 值 源代码网推荐 int pageNodesCount = pageNodes.Length - 2; 源代码网推荐 源代码网推荐 for (int i = 0; i < pageNodesCount; i++) 源代码网推荐 { 源代码网推荐 relativePath = "/.." + relativePath; 源代码网推荐 } 源代码网推荐 源代码网推荐 if (pageNodesCount > 0) 源代码网推荐 { 源代码网推荐 // 如果存在 ".." , 则把最前面的 "/" 去掉 源代码网推荐 relativePath = relativePath.Substring(1, relativePath.Length - 1); 源代码网推荐 } 源代码网推荐 源代码网推荐 return relativePath; 源代码网推荐 } 源代码网推荐 源代码网推荐 第二个方法显然是从第一个方法中的前部分抽取出来的,所以懒得去添加相关注释 :P 源代码网推荐 将Web站点下的绝对路径转换为虚拟路径 源代码网推荐 /**//// <summary> 源代码网推荐 /// 将Web站点下的绝对路径转换为虚拟路径 源代码网推荐 /// 注:非Web站点下的则不转换 源代码网推荐 /// </summary> 源代码网推荐 /// <param name="page">当前页面指针,一般为this</param> 源代码网推荐 /// <param name="specifiedPath">绝对路径</param> 源代码网推荐 /// <returns>虚拟路径, 型如: ~/</returns> 源代码网推荐 public static string ConvertSpecifiedPathToRelativePath(Page page, string specifiedPath) 源代码网推荐 { 源代码网推荐 string virtualPath = page.Request.ApplicationPath; 源代码网推荐 源代码网推荐 string pathRooted = HostingEnvironment.MapPath(virtualPath); 源代码网推荐 源代码网推荐 if (!Path.IsPathRooted(specifiedPath) || specifiedPath.IndexOf(pathRooted) == -1) 源代码网推荐 { 源代码网推荐 return specifiedPath; 源代码网推荐 } 源代码网推荐 源代码网推荐 if (pathRooted.Substring(pathRooted.Length - 1, 1) == "\") 源代码网推荐 { 源代码网推荐 specifiedPath = specifiedPath.Replace(pathRooted, "~/"); 源代码网推荐 } 源代码网推荐 else 源代码网推荐 { 源代码网推荐 specifiedPath = specifiedPath.Replace(pathRooted, "~"); 源代码网推荐 } 源代码网推荐 源代码网推荐 string relativePath = specifiedPath.Replace("\", "/"); 源代码网推荐 return relativePath; 源代码网推荐 } 源代码网推荐 源代码网推荐 将虚拟路径转绝对路就没什么好说的了, HttpRequest.MapPath 方法专门干这事 源代码网推荐 源代码网推荐 源代码网推荐 源代码网推荐 做人要厚道,请注明转自酷网动力(www.ASPCOOL.COM)。 源代码网推荐 源代码网供稿. |
