如何获取存储在内容文件夹.net中的图像的路径 [英] How to get the path to image stored in content folder .net
问题描述
我正在使用以下代码从Visual Studio的Content/img文件夹中获取图像:
I'm using this code to get an image from the Content/img folder in visual studio:
Image image = Image.FromFile(@"~\Content\img\toendra.JPG");
这给了我找不到文件的错误.但是,如果我给出图像的绝对路径,它将起作用:
This gives me the error that the file is not found. However if I give the absolute path to the image, it works:
Image image = Image.FromFile(@"C:\Users\Stijn\Source\Repos\groep11DotNet\p2groep11.Net\Content\img\toendra.JPG");
我的相对路径出了什么问题?
What is wrong with my relative path?
推荐答案
System.Drawing.Image.FromFile
不知道如何处理ASP.NET应用程序的根相对路径.因此,您必须使用中间函数将其转换为它可以理解的物理文件路径.
System.Drawing.Image.FromFile
doesn't know how to handle an ASP.NET application root relative path. So you have to use an intermediate function to convert it to a physical file path that it can understand.
Image image = Image.FromFile(HttpContext.Current.Server.MapPath("~/Content/img/toendra.JPG"));
注意,我将您的反斜杠转换为正斜杠(这是在URL中使用的正确符号),从而消除了对字符串文字的需求.
Notice I converted your backslashes to forward slashes (which are the correct symbols to use in a URL) and that eliminated the need for the string literal.
如果要大量使用它,可以制作一个helper实用程序类.
If you're going to use it a lot, might make a helper utility class.
public static class ImageHelper
{
public static Image LoadFromAspNetUrl(string url)
{
if(HttpContext.Current == null)
{
throw new ApplicationException("Can't use HttpContext.Current in non-ASP.NET context");
}
return Image.FromFile(HttpContext.Current.Server.MapPath(url));
}
}
用法:
Image myImage = ImageHelper.LoadFromAspNetUrl("~/Content/img/toendra.JPG");
这篇关于如何获取存储在内容文件夹.net中的图像的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!