How do I convert a file path to a URL in ASP.NET How do I convert a file path to a URL in ASP.NET asp.net asp.net

How do I convert a file path to a URL in ASP.NET


this is what i use:

private string MapURL(string path){    string appPath = Server.MapPath("/").ToLower();    return string.Format("/{0}", path.ToLower().Replace(appPath, "").Replace(@"\", "/")); }


As far as I know, there's no method to do what you want; at least not directly. I'd store the photosLocation as a path relative to the application; for example: "~/Images/". This way, you could use MapPath to get the physical location, and ResolveUrl to get the URL (with a bit of help from System.IO.Path):

string photosLocationPath = HttpContext.Current.Server.MapPath(photosLocation);if (Directory.Exists(photosLocationPath)){    string[] files = Directory.GetFiles(photosLocationPath, "*.jpg");    if (files.Length > 0)    {        string filenameRelative = photosLocation +  Path.GetFilename(files[0])           return Page.ResolveUrl(filenameRelative);    }}


The problem with all these answers is that they do not take virtual directories into account.

Consider:

Site named "tempuri.com/" rooted at c:\domains\sitevirtual directory "~/files" at c:\data\filesvirtual directory "~/files/vip" at c:\data\VIPcust\files

So:

Server.MapPath("~/files/vip/readme.txt")   = "c:\data\VIPcust\files\readme.txt"

But there is no way to do this:

MagicResolve("c:\data\VIPcust\files\readme.txt")    = "http://tempuri.com/files/vip/readme.txt"

because there is no way to get a complete list of virtual directories.