[Solved] Where to put a JSON file for processing?
# help-with-other
c
V13.2.2 I have a data import facility on an Umbraco site that, locally, takes a json file in the root of the project folder (i.e. Web/) and processes it. Now that the project has been deployed, the file structure is totally different and the file doesn't get hit at all. It's ended up in the root of the website files along with all the DLLs. My question is, where can I put it on the server (shared hosting), so it's not publicly accessible but can be hit. Here's the code that works locally:-
var jsonData = System.IO.File.ReadAllText("myfile.json");
Nice and simple and just works. Is there an equivalent in the deployed scenario? Thanks.
a
What do you mean be "can get hit"? That it's accessible from C#? If you need to save file on disk that aren't directly accessible on the website, you can save them somewhere inside the
~/umbraco/Data
folder. For illustrative purposes, I've put together a
JsonFileService
that supports reading from and writing to your
myfile.json
file assuming it's located inside `~/umbraco/Data`:
Copy code
csharp
using Microsoft.AspNetCore.Hosting;
using Umbraco.Extensions;

namespace LimboPackages;

public class JsonFileService {

    private readonly IWebHostEnvironment _webHostEnvironment;

    public JsonFileService(IWebHostEnvironment webHostEnvironment) {
        _webHostEnvironment = webHostEnvironment;
    }

    public string Read() {

        string path = _webHostEnvironment.MapPathContentRoot($"{Umbraco.Cms.Core.Constants.SystemDirectories.Data}/myfile.json");

        return File.ReadAllText(path);

    }

    public void Write(string contents) {

        string path = _webHostEnvironment.MapPathContentRoot($"{Umbraco.Cms.Core.Constants.SystemDirectories.Data}/myfile.json");

        File.WriteAllText(path, contents);

    }

}
The
Umbraco.Cms.Core.Constants.SystemDirectories.Data
constant in Umbraco is equal to
~/umbraco/Data
. The
_webHostEnvironment.MapPathWebRoot(...)
method returns the full path to the file in disk, relative to the content root of your site (which will typically be the root of your VS project). I haven't handled validation in the example, so the
Read
method will fail if the file doesn't already exist on disk. It might also be worth creating your own sub folder inside
~/umbraco/Data
to keep things organized. The
Write
method in my example could be updated to create the folder if it doesn't already exist.
c
It's just a one-off, but might be repeated, import facility to get data from a legacy system export file into Umbraco Nodes. Your path suggestion and example looks super helpful. Thanks. I'll give it a try now 🙂
@Anders Bjerner That worked a treat. Thank you so much 🙂
64 Views