关于.Net Core:.Net Core-发布时找不到参考文件

.Net Core - Referenced file is not found when publish

我将ImageSharp与.Net Core结合使用来处理某些图像。要加载图像和字体,请按以下步骤操作:

1
2
3
4
5
6
_image = Image.Load(@"Resources/imgs/quote_background.png");

_fonts = new FontCollection();
_font = _fonts.Install(@"Resources/fonts/Cousine-Italic.ttf");

// Image processing...

我的文件树如下:

1
2
3
4
5
6
7
8
9
    - Solution
    - - MyApp
    - - - Controllers
    - - - Models
    - - - - Code.cs // This is where the above code is
    - - - wwwroot
    - - - Resources
    - - - - imgs
    - - - - fonts

当我通过Visual Studio启动应用程序时,它运行良好,可以找到图像。但是,当我部署到AWS或本地IIS时,出现以下错误:

1
2
DirectoryNotFoundException: Could not find a part of the path 'C:\\inetpub\\wwwroot\\MyApp\
esources\\imgs\\quote_background.png'.

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

谢谢


您要确保将Resources文件夹中的文件标记为"复制到输出目录" ="如果更新则复制"

Property

这将确保发布网站时文件最终出现在输出中。


您需要使用IHostingEnvironment中的ContentRootPath,这需要您将IHostingEnvironment注入到控制器中,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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。