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

我正在使用此代码从visual studio中的Content / img文件夹中获取图像:

Image image = Image.FromFile(@"~\Content\img\toendra.JPG"); 

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

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

我的相对路径出了什么问题?

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

 Image image = Image.FromFile(HttpContext.Current.Server.MapPath("~/Content/img/toendra.JPG")); 

请注意,我将反斜杠转换为正斜杠(这是在URL中使用的正确符号),并且不需要字符串文字。

如果你要使用它很多,可能会成为一个帮助实用程序类。

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