sansactions
sansactions

Reputation: 243

Using files with your ASP.Net project

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

Upvotes: 0

Views: 75

Answers (1)

Maximilian K.
Maximilian K.

Reputation: 227

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;
}

Upvotes: 1

Related Questions