The easiest way to do this is to get rid of the physical application path. If you cannot do this in your code, just split it with the pathRaw variable. Like this:
public string GetVirtualPath( string physicalPath ) { if ( !physicalPath.StartsWith( HttpContext.Current.Request.PhysicalApplicationPath ) ) { throw new InvalidOperationException( "Physical path is not within the application root" ); } return "~/" + physicalPath.Substring( HttpContext.Current.Request.PhysicalApplicationPath.Length ) .Replace( "\\", "/" ); }
The code first checks to see if the path is in the root of the application. If not, there is no way to calculate the URL for the file, so an exception is thrown.
A virtual path is created by removing the physical path of the application, converting all backslashes to slashes, and prefixing the path with "~/" to indicate that it should be interpreted as relative to the root of the application.
After that, you can convert the virtual path to a relative path for output to the browser using ResolveClientUrl (virtualPath) .
source share