Search code examples
c#asp.net-coreasp.net-apicontroller

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


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?


Solution

  • Use IWebHostEnvirounment 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 IWebHostEnvirounment to your controller then get the content root folder as below:

    public class MyApiController : ControllerBase {
    
        private readonly IWebHostEnvirounment _hostingEnvirounment;
    
        public MyApiController(IWebHostEnvironment 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);
        }
    }