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.
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.
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.
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.
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.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With