In the new world of ASP.NET Core, when deploying, we have 2 folders appRoot and wwwroot
we usually place files below the wwwroot folder, which we intend to serve directly using HTTP requests. So if your json files should be filed directly, i.e. consumed on the client side js, then perhaps you placed them, otherwise you would use a different folder below appRoot.
Below I will tell you how to allow paths for both scenarios, that is, an example of code, how to save the json string in the folder below either appRoot or wwwroot. In both cases, consider your location as a virtual path relative to one of these folders, i.e. / Some / folder / path, where the first / represents either appRoot or wwwroot
public class MyFileProcessor { public MyFileProcessor(IHostingEnvironment env, IApplicationEnvironment appEnv) { hostingEnvironment = env; appEnvironment = appEnv; appRootFolder = appEnv.ApplicationBasePath; } private IHostingEnvironment hostingEnvironment; private IApplicationEnvironment appEnvironment; private string appRootFolder; public void SaveJsonToAppFolder(string appVirtualFolderPath, string fileName string jsonContent) { var pathToFile = appRootFolder + appVirtualFolderPath.Replace("/", Path.DirectorySeparatorChar.ToString()) + fileName; using (StreamWriter s = File.CreateText(pathToFile)) { await s.WriteAsync(jsonContent); } } public void SaveJsonToWwwFolder(string virtualFolderPath, string fileName string jsonContent) { var pathToFile = hostingEnvironment.MapPath(virtualFolderPath) + fileName; using (StreamWriter s = File.CreateText(pathToFile)) { await s.WriteAsync(jsonContent); } } }
source share