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?)

6
  • 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. Commented Feb 27, 2017 at 10:37
  • 1
    I normally embed the files as resources - see stackoverflow.com/questions/3314140/… and support.microsoft.com/en-gb/help/319292/… Commented Feb 27, 2017 at 10:38
  • 1
    var path = string.Concat(HostingEnvironment.MapPath(@"~\bin\"), filename); var json = File.ReadAllText(path); Commented Feb 27, 2017 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. Commented Feb 27, 2017 at 10:39
  • @LeszekRepie What is the "HostingEnvironment"? Commented Feb 27, 2017 at 10:45

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is for .Net Core isn't it?
Oh. Right. Sorry. I'm forgetting all the time, that .Net and .Net Core are not as compatible as I thought :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.