Absolute file path to relative URL

maxp picture maxp · Feb 1, 2010 · Viewed 17.2k times · Source

I've seen lots of tutorials on resolving a relative url to an absolute path, but i want to do the opposite: resolve an system absolute filepath into a relative url.

Is there a nice hack-free way to turn a filepath like c:\my_website_root\images\picture_a.jpg into images/picture_a.jpg

I've had a look at Uri.MakeRelative() but i dont think it will be of use in this case.

Edit: I've implemented it like this, still seems hacky (esp line#2)

var urlPath = new Uri(@"c:\mywebfolder\images\picture1.jpg");
var urlRoot = new Uri(Server.MapPath("~")+"/");
string relative = urlRoot.MakeRelativeUri(urlPath).ToString();

Answer

Oded picture Oded · Feb 1, 2010

In IIS, setup a virtual directory images and point it to c:\my_website_root\images\.

If your website is already directing to c:\my_website_root\, you don't need to do anything.