Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing local files with ASP.NET Core and MVC

With Asp.NET Core, The handy path-finding functions in Environment are gone. HttpContext and HttpServerUtility have been stripped. And the Application store within the Cache framework is gone. I can no longer assume (in code) that my server is using IIS or that it's even running on a Windows box.

And I don't have a database; I have a set of JSON files. Which, for reasons outside the scope of this question, cannot be stored in a database.

How do I read and write to files on the server?

like image 827
AndrewS Avatar asked Apr 06 '16 07:04

AndrewS


1 Answers

In the new ASP.NET Core world when we deploy we have 2 folders appRoot and wwwroot

we generally only put files below the wwwroot folder that we intend to serve directly with http requests. So if your json files are to be served directly ie consumed by client side js then maybe you would put them there, otherwise you would use a different folder below appRoot.

I will show below how to resolve paths for both scenarios, ie sample code how to save a json string to a folder below either appRoot or wwwroot. In both cases think of your location as a virtual path relative to one of those folders, ie /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);
        }

    }


}
like image 180
Joe Audette Avatar answered Oct 20 '22 03:10

Joe Audette