.Net Core - 发布时未找到引用文件
.Net Core - Referenced file is not found when publish
我正在使用带 .Net Core 的 ImageSharp 来处理一些图像。要加载图像和字体,我按如下方式进行:
_image = Image.Load(@"Resources/imgs/quote_background.png");
_fonts = new FontCollection();
_font = _fonts.Install(@"Resources/fonts/Cousine-Italic.ttf");
// Image processing...
我的文件树看起来像:
- Solution
- - MyApp
- - - Controllers
- - - Models
- - - - Code.cs // This is where the above code is
- - - wwwroot
- - - Resources
- - - - imgs
- - - - fonts
当我通过 visual studio 启动应用程序时,它工作正常,它找到了图像。但是,当我部署到 AWS 或我的本地 IIS 时,出现以下错误:
DirectoryNotFoundException: Could not find a part of the path 'C:\inetpub\wwwroot\MyApp\Resources\imgs\quote_background.png'.
引用此图片的正确方法是什么?
谢谢
您需要使用 IHostingEnvironment 中的 ContentRootPath,这需要您将 IHostingEnvironment 注入您的控制器,例如:
public class ImageController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public ImageController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public ActionResult Index()
{
var image = Image.Load(String.Format(@"{0}/Resources/imgs/quote_background.png",
_hostingEnvironment.ContentRootPath);
//etc...
}
}
还有 WebRootPath 可以让你到达 wwwroot。
您要确保将 Resources
文件夹中的文件标记为 'Copy to Output Directory' = 'Copy if newer'
这将确保在您发布网站时文件最终出现在您的输出中。
我正在使用带 .Net Core 的 ImageSharp 来处理一些图像。要加载图像和字体,我按如下方式进行:
_image = Image.Load(@"Resources/imgs/quote_background.png");
_fonts = new FontCollection();
_font = _fonts.Install(@"Resources/fonts/Cousine-Italic.ttf");
// Image processing...
我的文件树看起来像:
- Solution
- - MyApp
- - - Controllers
- - - Models
- - - - Code.cs // This is where the above code is
- - - wwwroot
- - - Resources
- - - - imgs
- - - - fonts
当我通过 visual studio 启动应用程序时,它工作正常,它找到了图像。但是,当我部署到 AWS 或我的本地 IIS 时,出现以下错误:
DirectoryNotFoundException: Could not find a part of the path 'C:\inetpub\wwwroot\MyApp\Resources\imgs\quote_background.png'.
引用此图片的正确方法是什么?
谢谢
您需要使用 IHostingEnvironment 中的 ContentRootPath,这需要您将 IHostingEnvironment 注入您的控制器,例如:
public class ImageController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public ImageController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public ActionResult Index()
{
var image = Image.Load(String.Format(@"{0}/Resources/imgs/quote_background.png",
_hostingEnvironment.ContentRootPath);
//etc...
}
}
还有 WebRootPath 可以让你到达 wwwroot。
您要确保将 Resources
文件夹中的文件标记为 'Copy to Output Directory' = 'Copy if newer'
这将确保在您发布网站时文件最终出现在您的输出中。