如何获取存储在内容文件夹.net中的图像的路径

1 c# asp.net

我正在使用以下代码从Visual Studio的Content / img文件夹中获取图像:

Image image = Image.FromFile(@"~\Content\img\toendra.JPG");
Run Code Online (Sandbox Code Playgroud)

这给了我找不到该文件的错误。但是,如果我给出图像的绝对路径,则可以使用:

Image image = Image.FromFile(@"C:\Users\Stijn\Source\Repos\groep11DotNet\p2groep11.Net\Content\img\toendra.JPG");
Run Code Online (Sandbox Code Playgroud)

我的相对路径有什么问题?

mas*_*son 5

System.Drawing.Image.FromFile不知道如何处理ASP.NET应用程序的根相对路径。因此,您必须使用中间函数将其转换为它可以理解的物理文件路径。

Image image = Image.FromFile(HttpContext.Current.Server.MapPath("~/Content/img/toendra.JPG"));
Run Code Online (Sandbox Code Playgroud)

注意,我将您的反斜杠转换为正斜杠(这是在URL中使用的正确符号),从而消除了对字符串文字的需求。

如果您打算经常使用它,则可以制作一个helper实用程序类。

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

Image myImage = ImageHelper.LoadFromAspNetUrl("~/Content/img/toendra.JPG");
Run Code Online (Sandbox Code Playgroud)