如何在ASP.NET中将文件路径转换为URL

时间:2020-03-05 18:40:41  来源:igfitidea点击:

基本上,我有一些代码来检查特定目录,以查看是否有图像,如果有,我想将图像的URL分配给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;
    }
}

解决方案

回答

据我所知,没有哪个函数可以做到这一点(也许我们正在寻找MapPath的逆函数?)。我很想知道是否存在这样的功能。在此之前,我只需要获取GetFiles返回的文件名,删除路径,并在URL根前面添加。这可以一般地完成。

回答

我认为这应该有效。它可能在斜杠上关闭了。不知道是否需要它们。

string url = Request.ApplicationPath + "/" + photosLocation + "/" + files[0];

回答

据我所知,没有办法做你想做的事。至少不是直接。我会将" photosLocation"存储为相对于应用程序的路径;例如:""〜/ Images /"。这样,我们可以使用MapPath获取物理位置,并使用ResolveUrl获取URL(在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);
    }
}

回答

也许这不是最好的方法,但是它可行。

// Here is your path
String p = photosLocation + "whatever.jpg";

// Here is the page address
String pa = Page.Request.Url.AbsoluteUri;

// Take the page name    
String pn = Page.Request.Url.LocalPath;

// Here is the server address    
String sa = pa.Replace(pn, "");

// Take the physical location of the page    
String pl = Page.Request.PhysicalPath;

// Replace the backslash with slash in your path    
pl = pl.Replace("\", "/");    
p = p.Replace("\", "/");

// Root path     
String rp = pl.Replace(pn, "");

// Take out same path    
String final = p.Replace(rp, "");

// So your picture's address is    
String path = sa + final;

编辑:好的,有人标记为没有帮助。一些解释:采用当前页面的物理路径,将其分为两部分:服务器和目录(例如c:\ inetpub \ whatever.com \ whatever)和页面名称(例如/Whatever.aspx)。图像的物理路径应包含服务器的路径,因此请"减去"它们,仅保留图像相对于服务器路径的路径(例如:\ design \ picture.jpg)。将反斜杠替换为斜杠,并将其添加到服务器的url中。

回答

我已经接受了Fredriks的答案,因为它似乎可以用最少的精力来解决问题,但是Request对象似乎并未包含ResolveUrl方法。
可以通过Page对象或者Image控件对象进行访问:

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

如果我们按原样使用静态类,则可以使用VirtualPathUtility:

myImage.ImageUrl = VirtualPathUtility.ToAbsolute(photoURL);