Adding Async methods to verious services
This commit is contained in:
@@ -13,48 +13,69 @@ public class DefaultLocalFileManager : ISzFileManager
|
||||
Directory.CreateDirectory(TemplatesPath);
|
||||
}
|
||||
|
||||
#region Synchronous Methods
|
||||
public bool SaveFile(string path, string fileContent)
|
||||
{
|
||||
try
|
||||
{
|
||||
var dir = Path.GetDirectoryName(path);
|
||||
if (dir is null) return false;
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
PrepareDirectory(path);
|
||||
File.WriteAllText(path, fileContent);
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"Error saving file: {e.Message}");
|
||||
SZ.Logger.LogError($"Error saving file: {e.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public string? LoadFile(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return File.ReadAllText(path);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"Error loading file: {e.Message}");
|
||||
return null;
|
||||
}
|
||||
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
|
||||
{
|
||||
File.Delete(path);
|
||||
PrepareDirectory(path);
|
||||
// Use the native async File I/O
|
||||
await File.WriteAllTextAsync(path, fileContent, ct);
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
SZ.Logger.LogError("LocalFileManager: Could not delete file. " + e.Message);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user