Files
sessionzero-cs/SzCore/Defaults/DefaultLocalFileManager.cs

81 lines
2.2 KiB
C#

namespace SzCore.Defaults;
public class DefaultLocalFileManager : ISzFileManager
{
public string DataPath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data");
public string DatasetsPath => Path.Combine(DataPath, "datasets");
public string TemplatesPath => Path.Combine(DataPath, "templates");
public DefaultLocalFileManager()
{
Directory.CreateDirectory(DataPath);
Directory.CreateDirectory(DatasetsPath);
Directory.CreateDirectory(TemplatesPath);
}
#region Synchronous Methods
public bool SaveFile(string path, string fileContent)
{
try
{
PrepareDirectory(path);
File.WriteAllText(path, fileContent);
return true;
}
catch (Exception e)
{
SZ.Logger.LogError($"Error saving file: {e.Message}");
return false;
}
}
public string? LoadFile(string path)
{
try { return File.ReadAllText(path); }
catch { return null; }
}
public bool DeleteFile(string path)
{
try { File.Delete(path); return true; }
catch { return false; }
}
#endregion
#region Asynchronous Methods
public async Task<bool> SaveFileAsync(string path, string fileContent, CancellationToken ct = default)
{
try
{
PrepareDirectory(path);
// Use the native async File I/O
await File.WriteAllTextAsync(path, fileContent, ct);
return true;
}
catch (Exception e)
{
SZ.Logger.LogError($"Error saving file async: {e.Message}");
return false;
}
}
public async Task<string?> LoadFileAsync(string path, CancellationToken ct = default)
{
try
{
if (!File.Exists(path)) return null;
return await File.ReadAllTextAsync(path, ct);
}
catch { return null; }
}
#endregion
private void PrepareDirectory(string filePath)
{
var dir = Path.GetDirectoryName(filePath);
if (dir != null && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
}