Read solution data files ASP.Net Core

Martin Kearn picture Martin Kearn · Mar 7, 2016 · Viewed 52.6k times · Source

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.

Answer

Martin Kearn picture Martin Kearn · Mar 8, 2016

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