教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 asp.net将绝对路径转换为虚拟路径的代码举例

asp.net将绝对路径转换为虚拟路径的代码举例

发布时间:2016-05-23   编辑:jiaochengji.com
本文介绍下,asp.net实现将绝对路径转换为虚拟路径的方法,有需要的朋友参考下吧。

本文给出的代码,实现如下功能:
将Web站点下的绝对路径转换为相对于指定页面的虚拟路径。

代码如下:

/// <summary>
/// 将Web站点下的绝对路径转换为相对于指定页面的虚拟路径
/// </summary>
/// <param name="page">当前页面指针,一般为this</param>
/// <param name="specifiedPath">绝对路径</param>
/// <returns>虚拟路径, 型如: http://www.jbxue.com/</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;
}

方法法二,显然是从第一个方法中的前部分抽取出来的。

方法二,
将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方法即可。

您可能感兴趣的文章:
asp.net将绝对路径转换为虚拟路径的代码举例
Global.asax取物理路径/取绝对路径代码
asp.net编程篇之Request对象和虚拟路径
java.io.File中的绝对路径和相对路径.
file.getPath() getAbsolutePath() getCanonicalPath()区别
使用http module 对url进行重写的方法
ASP.NET MasterPage中图片路径的解决办法
Server.MapPath方法的应用方法
js获取网站路径(站点与虚拟目录)的代码
jsp中获取绝对路径和相对路径方法

关键词: 路径   
[关闭]
~ ~