Skip to content

Instantly share code, notes, and snippets.

@floko84
Created January 6, 2022 23:27
Show Gist options
  • Save floko84/5ce713e8b58693439772da7f5e44a8a8 to your computer and use it in GitHub Desktop.
Save floko84/5ce713e8b58693439772da7f5e44a8a8 to your computer and use it in GitHub Desktop.
Reverse of HttpServerUtility.MapPath or HostingEnvironment.MapPath, maps a physical path to an absolute virtual path.
using System;
using System.Web;
using System.Web.Hosting;
public static class VirtualPathHelper
{
/// <summary>
/// Returns the virtual path that corresponds to the specified physical file path.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string MapVirtualPath(string path)
{
var relativePath = new Uri(HostingEnvironment.ApplicationPhysicalPath)
.MakeRelativeUri(new Uri(path))
.ToString();
var appPath = VirtualPathUtility.AppendTrailingSlash(HostingEnvironment.ApplicationVirtualPath);
return string.IsNullOrEmpty(relativePath)
? appPath
: VirtualPathUtility.Combine(appPath, relativePath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment