Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

url

asp.net

image

Basically I have some code to check a specific directory to see if an image is there and if so I want to assign a URL to the image to an ImageControl.

if (System.IO.Directory.Exists(photosLocation)) {     string[] files = System.IO.Directory.GetFiles(photosLocation, "*.jpg");     if (files.Length > 0)     {         // TODO: return the url of the first file found;     } } 
like image 673
Andy Rose Avatar asked Aug 19 '08 11:08

Andy Rose


2 Answers

this is what i use:

private string MapURL(string path) {     string appPath = Server.MapPath("/").ToLower();     return string.Format("/{0}", path.ToLower().Replace(appPath, "").Replace(@"\", "/"));  } 
like image 97
Rafael Herscovici Avatar answered Sep 22 '22 01:09

Rafael Herscovici


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);     } } 
like image 43
Fredrik Kalseth Avatar answered Sep 23 '22 01:09

Fredrik Kalseth