如何转换的文件路径在ASP.NET中的URL [英] How do I convert a file path to a URL in ASP.NET

查看:114
本文介绍了如何转换的文件路径在ASP.NET中的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一些code检查某一特定目录,看看如果图像是存在的,如果是的话我想一个URL的图像分配到ImageControl。

 如果(System.IO.Directory.Exists(photosLocation))
{
    字符串[] =文件System.IO.Directory.GetFiles(photosLocation,* .JPG);
    如果(files.Length大于0)
    {
        // TODO:返回找到的第一个文件的URL;
    }
}


解决方案

据我所知,有没有方法做你想做的;至少不直接。我保存 photosLocation 为相对于应用程序的路径;例如:〜/图片/。通过这种方式,你可以使用的MapPath得到的物理位置,而 RESOLVEURL 来获取URL(从 System.IO.Path一点帮助

 字符串photosLocationPath = HttpContext.Current.Server.MapPath(photosLocation);
如果(Directory.Exists(photosLocationPath))
{
    字符串[] =文件Directory.GetFiles(photosLocationPath,* .JPG);
    如果(files.Length大于0)
    {
        字符串filenameRelative = photosLocation + Path.GetFilename(文件[0])
        返回Page.ResolveUrl(filenameRelative);
    }
}

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

解决方案

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

这篇关于如何转换的文件路径在ASP.NET中的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆