Saving local files using ASP.NET Core and MVC

Asp.NET Core lacks convenient path-finding features in the environment. HttpContext and HttpServerUtility have been removed. And the application store within Cache has disappeared. I can no longer assume (in code) that my server is using IIS or that it even works in a Windows window.

And I do not have a database; I have a set of JSON files. Which, for reasons beyond the scope of this question, cannot be stored in the database.

How to read and write files on the server?

+6
source share
1 answer

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); } } } 
+7
source

All Articles