How do I read in a file from disc during runtime in my WebAPI .NET Core [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-12-13 03:54:30

问题


In my solution I have a file called beep.png directly in the root, right next to Startup.cs file. I changed its properties to always copy. I activated UseFileServer and opted in to browse the directory structure to be sure.

However, when I run the code Image.FromFile("beep.png");, I only get the error that the file isn't found.

System.IO.FileNotFoundException
Message=C:\Program Files\IIS Express\beep.png

How can I enable the file to be accessible?


回答1:


Use IHostingEnvirounment to get the root content path (technicaly the project folder), or to get the web root path (the wwwroot folder under project folder).

_hostingEnvirounment.ContentRootPath will return:

D:\Hosting\ProjectFolder

_hostingEnvirounment.WebRootPath will rturn:

D:\Hosting\ProjectFolder\wwwroot

So in your case; inject IHostingEnvirounment to your controller then get the content root folder as below:

public class MyApiController : ControllerBase {

    private readonly IHostingEnvirounment _hostingEnvirounment;

    public MyApiController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    // get image from project root folder \ProjectFolder\
    public Image GetImageFromContentRoot(string name) {

        // e.g.: imgPath = "D:\\Hosting\\ProjectFolder\\beep.png"
        var imgPath = Path.Combine(_hostingEnvirounment.ContentRootPath, name);

        return Image.FromFile(imgPath);
    }

    //get image from projects wwwroot folder
     public Image GetImageFromWebRoot(string name) {

        // e.g.: imgPath = "D:\\Hosting\\ProjectFolder\\wwwroot\\beep.png"
        var imgPath = Path.Combine(_hostingEnvirounment.WebRootPath, name);

        return Image.FromFile(imgPath);
    }
}


来源:https://stackoverflow.com/questions/54338080/how-do-i-read-in-a-file-from-disc-during-runtime-in-my-webapi-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!