I have an ASP.NET Core (1.0-rc1-final) MVC solution and I wish to store a simple text file within the project which contain a list of strings which I read into a string array in my controller.
Where should I store this file in my project and how do I read those files in my controllers?
In ASP.net 4.x I'd have used the app_data
folder and done something like this
string path = Server.MapPath("~/App_Data/File.txt");
string[] lines = System.IO.File.ReadAllLines(path);
But Server.MapPath
does not seem to be valid in ASP.Net Core 1 and I'm not sure that the app_data
folder is either.
I found a simple solution to this.
Firstly, you can create a folder anywhere in your solution, you do not have to stick to the conventions like 'app_data' from .net 4.x.
In my scenario, I created a folder called 'data' at the root of my project, I put my txt file in there and used this code to read the contents to a string array
var owners = System.IO.File.ReadAllLines(@"..\data\Owners.txt");
You can get the enviroment with Dependency Injection in your controller:
using Microsoft.AspNetCore.Hosting;
....
public class HomeController: Controller
{
private IHostingEnvironment _env;
public HomeController(IHostingEnvironment env)
{
_env = env;
}
...
Then you can get the wwwroot location in your actions: _env.WebRootPath
var owners = System.IO.File.ReadAllLines(System.IO.Path.Combine(_env.WebRootPath,"File.txt"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With