Craig100
04/13/2024, 11:19 AMvar jsonData = System.IO.File.ReadAllText("myfile.json");
Nice and simple and just works. Is there an equivalent in the deployed scenario?
Thanks.Anders Bjerner
04/13/2024, 12:33 PM~/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`:
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.Craig100
04/13/2024, 12:47 PMCraig100
04/13/2024, 1:18 PM