2017-07-16 64 views
0

使用ImageSharp和.Net Core处理某些图像。以如下加载我做的图像和字体:.Net Core - 发布时未找到引用的文件

_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'. 

什么是引用该图像的正确方法?

感谢

回答

1

您需要使用ContentRootPath从IHostingEnvironment,这就需要你注入的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文件。

+0

嗨马特,谢谢你的回答。我照你说的做了,但仍然有同样的错误。它似乎映射到以前相同的目录...当我发布项目Resource文件夹确​​实没有生成...你认为我必须配置的东西......? –

+0

好的,看到其他答案和[这一个](https://stackoverflow.com/a/42713770/934407),你的图像实际上是发布? – Matt

+0

谢谢马特...它确实解决了,但我不得不手动编辑我的.csproj,因为Visual Studio在我尝试设置属性时提示错误... –

1

你要确保你标志着你的Resources文件夹中的文件作为“复制到输出目录” =“复制,如果新”

Property screen shot showing copy to output directy set to copy if newer

,将确保该文件最终在你的输出当你发布该网站时。