最近在做一个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("\", "/").Substring(1, specifiedPath.Length - 1);
return relativePath;
}
备注: string relativePath = specifiedPath.Replace("\", "/").Substring(1, specifiedPath.Length - 1); 里面的 Substring(1, specifiedPath.Length - 1)是我自己加的。根据自己需求。原来是string relativePath = specifiedPath.Replace("\", "/");