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

2019-01-17 19:20发布

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

10条回答
做自己的国王
2楼-- · 2019-01-17 19:47

So far as I know there's no single function which does this (maybe you were looking for the inverse of MapPath?). I'd love to know if such a function exists. Until then, I would just take the filename(s) returned by GetFiles, remove the path, and prepend the URL root. This can be done generically.

查看更多
乱世女痞
3楼-- · 2019-01-17 19:48

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);
    }
}
查看更多
仙女界的扛把子
4楼-- · 2019-01-17 19:56

The simple solution seems to be to have a temporary location within the website that you can access easily with URL and then you can move files to the physical location when you need to save them.

查看更多
地球回转人心会变
5楼-- · 2019-01-17 19:56

For get the left part of the URL:

?HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)
"http://localhost:1714"

For get the application (web) name:

?HttpRuntime.AppDomainAppVirtualPath
"/"

With this, you are available to add your relative path after that obtaining the complete URL.

查看更多
登录 后发表回答