0

I am pretty new to ASP.Net and I am tying to access a couple JSON files in my directory. In my normal Visual Studio projects I could store these files in /bin/debug, where do i store these files here? I heard you have "App_Data" but i don't understand how i would configure this.

I tried:

string JsonString = File.ReadAllText("~/App_Data/" + filename); (stored file under self created App_Data map in Project/Project/)
string JsonString = File.ReadAllText(filename);

error: enter image description here (I do realise it says where i should store it but isn't there a better way to store these files in my project directoy?)

sansactions
  • 215
  • 5
  • 17
  • `App_Data` is just a folder, there's no need to "configure" it. However, you do need to use `MapPath` to convert `~/App_Data` to a real physical path. – DavidG Feb 27 '17 at 10:37
  • 1
    I normally embed the files as resources - see http://stackoverflow.com/questions/3314140/how-to-read-embedded-resource-text-file and https://support.microsoft.com/en-gb/help/319292/how-to-embed-and-access-resources-by-using-visual-c – phooey Feb 27 '17 at 10:38
  • 1
    var path = string.Concat(HostingEnvironment.MapPath(@"~\bin\"), filename); var json = File.ReadAllText(path); – Leszek P Feb 27 '17 at 10:39
  • @phooey The downside of that is that it makes the resource fixed which is not useful if you need to edit the file. – DavidG Feb 27 '17 at 10:39
  • @LeszekRepie What is the "HostingEnvironment"? – sansactions Feb 27 '17 at 10:45
  • I had to put a reference to System.Web.Hosting, thnx for the info people. – sansactions Feb 27 '17 at 11:18

1 Answers1

1

In .Net Core I'm using the IHostingEnvironment to get the Root Path of my Application. Then you can do somethink like Path.Combine(_hostingEnvironment.ContentRootPath, "myfolder", filename) to get the path of the file. Then you can use File.ReadAllText with that path.

To get the IHostingEnvironment you have to add it as an Parameter in the constructor:

private readonly IHostingEnvironment _hostingEnvironment;

public MyController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
}
Maximilian K.
  • 227
  • 4
  • 16