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

113,185

Solution 1

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);
    }
}

Solution 2

this is what i use:

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

Solution 3

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\site
virtual directory "~/files" at c:\data\files
virtual 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.

Solution 4

I've accepted Fredriks answer as it appears to solve the problem with the least amount of effort however the Request object doesn't appear to conatin the ResolveUrl method. This can be accessed through the Page object or an Image control object:

myImage.ImageUrl = Page.ResolveUrl(photoURL);
myImage.ImageUrl = myImage.ResolveUrl(photoURL);

An alternative, if you are using a static class as I am, is to use the VirtualPathUtility:

myImage.ImageUrl = VirtualPathUtility.ToAbsolute(photoURL);

Solution 5

This worked for me:

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath + "ImageName";
Share:
113,185

Related videos on Youtube

Andy Rose
Author by

Andy Rose

Web developer that started with ASP 3.0 and moved onto ASP.NET. Currently dabbling with ASP.NET MVC and trying to get a better understanding of CSS and jQuery.

Updated on January 13, 2020

Comments

  • Andy Rose
    Andy Rose over 4 years

    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;
        }
    }
    
  • Jared
    Jared over 14 years
    I can't find the ResolveUrl member of HttpRequest in the documentation for any of the .Net versions. Are you using ASP.Net MVC?
  • Andy Rose
    Andy Rose about 14 years
    @Fredrik As Jared has pointed out the HttpRequest object doesn't have this method. It can be found in the Page object or a web control object. Could you edit your answer to reflect this?
  • B2K
    B2K about 7 years
    Thanks for this, here is it as an extension method on Server - public static string MapUrl(this HttpServerUtilityBase Server, string path)
  • Concrete Gannet
    Concrete Gannet almost 6 years
    There's a security issue. In general, one web application should not be able to do anything with the server outside its own web root. If that is really what you want, you could do it by querying the IIS metabase, something like this: stackoverflow.com/questions/4710187/… . But your web app would need to run with dangerously high privileges. If two web applications need to exchange files, better to implement services for them to do so.
  • KADEM Mohammed
    KADEM Mohammed almost 6 years
    Seems that this one is the right answer and cleaner ! plz upvote
  • mike
    mike about 5 years
    Excellent answer! should have more up-votes. In more detail, you need a switch to deal with the AppDomainAppVirtualPath, because if the website is on the root, the VirtualPath will be an empty string, so no slash needed before filename, if the VirtualPath is filled out, you need to add an extra slash. string sVPath = HttpRuntime.AppDomainAppVirtualPath; if (sVPath.Length > 0) sVPath += "/"; string sCSSURL = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Autho‌​rity) + sVPath + "myImage.jpg";
  • Ross Presser
    Ross Presser over 4 years
    Conceivably, the mapping might not be unique. Two virtual directories could be mapped to the same NTFS folder.