<p>If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the <strong>fastest</strong> way to convert that absolute path back into a relative web path?</p>

[{'answer_id': 3178, 'author': 'Yaakov Ellis', 'author_id': 51, 'author_profile': 'https://Stackoverflow.com/users/51', 'pm_score': 2, 'selected': False, 'text': '<p>If you used Server.MapPath, then you should already have the relative web path. According to the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx" rel="nofollow noreferrer">MSDN documentation</a>, this method takes one variable, <em>path</em>, which is the virtual path of the Web server. So if you were able to call the method, you should already have the relative web path immediately accessible. </p>\n'}, {'answer_id': 3218, 'author': 'GateKiller', 'author_id': 383, 'author_profile': 'https://Stackoverflow.com/users/383', 'pm_score': 7, 'selected': True, 'text': '<p>Perhaps this might work:</p>\n\n<pre><code>String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);\n</code></pre>\n\n<p><em>I\'m using c# but could be adapted to vb.</em></p>\n'}, {'answer_id': 5222928, 'author': 'Canoas', 'author_id': 358580, 'author_profile': 'https://Stackoverflow.com/users/358580', 'pm_score': 5, 'selected': False, 'text': '<p>Wouldn\'t it be nice to have <strong>Server.RelativePath(path)</strong>?</p>\n\n<p>well, you just need to extend it ;-)</p>\n\n<pre><code>public static class ExtensionMethods\n{\n    public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)\n    {\n        return path.Replace(context.ServerVariables["APPL_PHYSICAL_PATH"], "~/").Replace(@"\\", "/");\n    }\n}\n</code></pre>\n\n<p>With this you can simply call</p>\n\n<pre><code>Server.RelativePath(path, Request);\n</code></pre>\n'}, {'answer_id': 10462610, 'author': 'AlexCuse', 'author_id': 794, 'author_profile': 'https://Stackoverflow.com/users/794', 'pm_score': 4, 'selected': False, 'text': '<p>I know this is old but I needed to account for virtual directories (per @Costo\'s comment).  This seems to help:</p>\n\n<pre><code>static string RelativeFromAbsolutePath(string path)\n{\n    if(HttpContext.Current != null)\n    {\n        var request = HttpContext.Current.Request;\n        var applicationPath = request.PhysicalApplicationPath;\n        var virtualDir = request.ApplicationPath;\n        virtualDir = virtualDir == "/" ? virtualDir : (virtualDir + "/");\n        return path.Replace(applicationPath, virtualDir).Replace(@"\\", "/");\n    }\n\n    throw new InvalidOperationException("We can only map an absolute back to a relative path if an HttpContext is available.");\n}\n</code></pre>\n'}, {'answer_id': 31021328, 'author': 'Pierre Chavaroche', 'author_id': 1928513, 'author_profile': 'https://Stackoverflow.com/users/1928513', 'pm_score': 3, 'selected': False, 'text': '<p>I like the idea from Canoas. Unfortunately I had not "HttpContext.Current.Request" available (BundleConfig.cs).</p>\n\n<p>I changed the methode like this:</p>\n\n<pre><code>public static string RelativePath(this HttpServerUtility srv, string path)\n{\n     return path.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\\", "/");\n}\n</code></pre>\n'}, {'answer_id': 53850472, 'author': 'Lapenkov Vladimir', 'author_id': 4404269, 'author_profile': 'https://Stackoverflow.com/users/4404269', 'pm_score': 0, 'selected': False, 'text': '<p>For asp.net core i wrote helper class to get pathes in both directions.</p>\n\n<pre><code>public class FilePathHelper\n{\n    private readonly IHostingEnvironment _env;\n    public FilePathHelper(IHostingEnvironment env)\n    {\n        _env = env;\n    }\n    public string GetVirtualPath(string physicalPath)\n    {\n        if (physicalPath == null) throw new ArgumentException("physicalPath is null");\n        if (!File.Exists(physicalPath)) throw new FileNotFoundException(physicalPath + " doesn\'t exists");\n        var lastWord = _env.WebRootPath.Split("\\\\").Last();\n        int relativePathIndex = physicalPath.IndexOf(lastWord) + lastWord.Length;\n        var relativePath = physicalPath.Substring(relativePathIndex);\n        return $"/{ relativePath.TrimStart(\'\\\\\').Replace(\'\\\\\', \'/\')}";\n    }\n    public string GetPhysicalPath(string relativepath)\n    {\n        if (relativepath == null) throw new ArgumentException("relativepath is null");\n        var fileInfo = _env.WebRootFileProvider.GetFileInfo(relativepath);\n        if (fileInfo.Exists) return fileInfo.PhysicalPath;\n        else throw new FileNotFoundException("file doesn\'t exists");\n    }\n</code></pre>\n\n<p>from Controller or service inject FilePathHelper and use:</p>\n\n<pre><code>var physicalPath = _fp.GetPhysicalPath("/img/banners/abro.png");\n</code></pre>\n\n<p>and versa</p>\n\n<pre><code>var virtualPath = _fp.GetVirtualPath(physicalPath);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/3164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192/']