I had earlier written a quick and dirty method to convert a Physical path to a virtual path (aka a url) that can be used on the client after passing through ASP.NET’s ResolveUrl method. Without much talking, here’s the method:

 

{syntaxhighlighter brush: csharp;fontsize: 100; first-line: 1; }public static class Globals
{
private static string applicationPath;

static Globals ()
{
Globals.applicationPath = System.Web.Hosting.HostingEnvironment.MapPath(“~/”);
}

public static string resolveVirtual (string physicalPath)
{
string url=physicalPath.Substring(Globals.applicationPath.Length).Replace(‘\\’, ‘/’).Insert(0, “~/”);
return (url);
}
}{/syntaxhighlighter}

The method Globals.resolveVirtual accepts an absolute physical path (the physical path should be an absolute path and not a relative one), strips out the path to application root from it, and then converts it to an app-relative url. You can pass it through ResolveUrl method to get a url usable on the client.

There’s a caveat though. This would work only if your ASP.NET application does not have nested virtual directories in it. IIS would allow you to define your application as a virtual directory and further create nested virtual directories that are physically outside your application’s root folder. The above method would not work for such nested virtual directory paths.