Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read solution data files ASP.Net Core

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.

like image 483
Martin Kearn Avatar asked Mar 07 '16 11:03

Martin Kearn


2 Answers

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

like image 128
Martin Kearn Avatar answered Nov 10 '22 07:11

Martin Kearn


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"));
like image 24
Pieter van Kampen Avatar answered Nov 10 '22 06:11

Pieter van Kampen