andreasperelli
andreasperelli

Reputation: 1034

File path to be accessible by controller in ASP.NET MVC

I'm using the following code to access a JSON file:

        using (var reader = new StreamReader("Areas/Communications/Data/Codes.json"))
        {

        }

The file, as reported in the code, is in the MVC folder 'Data' and the controller is in:

Areas/Communications/Controllers/MyController.cs.

When I execute the code, the following exception is thrown:

 System.IO.DirectoryNotFoundException: Can't find a part of the path 'c:\windows\system32\inetsrv\Areas\Communications\Data\Codes.json'.

Is this the good practice to read a file from the controller or I'm missing something?

Upvotes: 0

Views: 95

Answers (2)

andreasperelli
andreasperelli

Reputation: 1034

Solved with:

using (var reader = new StreamReader(Server.MapPath("~/Areas/Communications/Data/Codes.json")))

Upvotes: 0

Bastian Noffer
Bastian Noffer

Reputation: 51

You should not put content files into your ASP.Net folder structure, since this is not persisted when you deploy your application.

If you want files to be accessible during runtime that you do not want to have in your wwwroot create a data directory in your project and put your content files there, also mark them as content in your solution and to copy them during the build process.

Then use

Path.Combine(AppContext.BaseDirectory, /data/path/to/your.json)

to retrieve the file path from your applications current working directory.

Upvotes: 0

Related Questions