And*_*ose 46 asp.net url image
基本上我有一些代码来检查特定的目录,看看是否有图像,如果是,我想将图像的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;
}
}
Run Code Online (Sandbox Code Playgroud)
Dem*_*tic 16
这是我用的:
private string MapURL(string path)
{
string appPath = Server.MapPath("/").ToLower();
return string.Format("/{0}", path.ToLower().Replace(appPath, "").Replace(@"\", "/"));
}
Run Code Online (Sandbox Code Playgroud)
Fre*_*eth 13
据我所知,没有办法做你想做的事情; 至少不是直接的.我将它存储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);
}
}
Run Code Online (Sandbox Code Playgroud)
Ros*_*ser 11
所有这些答案的问题在于它们不考虑虚拟目录.
考虑:
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
Run Code Online (Sandbox Code Playgroud)
所以:
Server.MapPath("~/files/vip/readme.txt")
= "c:\data\VIPcust\files\readme.txt"
Run Code Online (Sandbox Code Playgroud)
但是没有办法做到这一点:
MagicResolve("c:\data\VIPcust\files\readme.txt")
= "http://tempuri.com/files/vip/readme.txt"
Run Code Online (Sandbox Code Playgroud)
因为无法获得完整的虚拟目录列表.
我已经接受了Fredriks的答案,因为它似乎以最少的努力解决了问题,但是Request对象似乎并没有使用ResolveUrl方法.这可以通过Page对象或Image控件对象访问:
myImage.ImageUrl = Page.ResolveUrl(photoURL);
myImage.ImageUrl = myImage.ResolveUrl(photoURL);
Run Code Online (Sandbox Code Playgroud)
如果你像我一样使用静态类,另一种方法是使用VirtualPathUtility:
myImage.ImageUrl = VirtualPathUtility.ToAbsolute(photoURL);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
97020 次 |
最近记录: |