Thumbnail image

How to Access Files in the Backend on .NET Core?

Hi, in this article, we will look at how we can access files when we want to do operations such as reading, writing, etc. with .NET Core.

How to access a file in wwwroot?

The first thing you need to do is to set the IWebHostEnvironment interface as a parameter to the construction field of your page or class and set it as private readonly. In this way, we can use it wherever we want after the page is initialized.

 private   readonly  IWebHostEnvironment _webHostEnvironment; 
 public  IndexModel(IWebHostEnvironment webHostEnvironment)
 {
     _webHostEnvironment = webHostEnvironment;
 }

In this way, we will set the Web Host Environment private object while the page is loading. Now when we want to access a file path we can do it this way.

_webHostEnvironment.WebRootPath + $@"\files\pdfs\{PDFName}.pdf"

How to access a file in the project’s directory?
This is a much simpler MapAbsolutePath method, at the end of the string. its use is slightly different, but simple and catchy.

var dbPath = "~/db.sqlite".MapAbsolutePath();

In general, we have seen how we can access file paths from the back-end when you want to read or write files.

You can support by writing a comment, I wish you a pleasant reading.