How do I read in a file from disc during runtime i

2019-08-27 01:51发布

问题:

This question already has an answer here:

  • How do I read a local file in my ASP.NET Core project 2 answers

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