Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.NET Core json file or data path - where to put it

I am in .NET MVC, I wish to read a JSON file like so:

 JSON = System.IO.File.ReadAllText("companyInfo.json");

However I can't get a path going. I don't care where I put the json file, so I am asking for both a recommended place to put it as well as the path string to use.

like image 244
Devin Andres Salemi Avatar asked Jul 20 '17 20:07

Devin Andres Salemi


People also ask

Where do I put secret json?

Configure User Secrets with secrets. json for your project. You won't see the file inside the solution explorer as it's saved within your roaming data. The exact path for the file is: C:\Users\ < username > \AppData\Roaming\Microsoft\UserSecrets\ < id > where <username> of course, would be your username.

Where are .NET Core files stored?

Static files are stored within the project's web root directory. The default directory is {content root}/wwwroot , but it can be changed with the UseWebRoot method.

Why do we have wwwroot folder?

By default, the wwwroot folder in the ASP.NET Core project is treated as a web root folder. Static files can be stored in any folder under the web root and accessed with a relative path to that root.

What are the json files in .NET Core?

json file is an application configuration file used to store configuration settings such as database connections strings, any application scope global variables, etc. If you open the ASP.NET Core appsettings. json file, then you see the following code by default which is created by visual studio.


1 Answers

you can Try to use the following with asp.net core

 public class HomeController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public HomeController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public ActionResult Index()
        {

            string contentRootPath = _hostingEnvironment.ContentRootPath;
               var   JSON = System.IO.File.ReadAllText( contentRootPath + "/companyInfo.json");
            return null; 
        }
    }

Update The contentrootPath will give you the base root of your application

Something like this ContentRoot: C:\MyApp\ note it depends on the OS you can create a data folder and use Path.Combine to build your absolute path

But you can use the WebRootPath

string webRootPath = _hostingEnvironment.WebRootPath; 

if you want it to be served from The web root which is the root directory from which static content is served,

like image 78
BRAHIM Kamel Avatar answered Oct 16 '22 12:10

BRAHIM Kamel