feat: implement read and write methods for json file storage provider

This commit is contained in:
Stevan Freeborn
2026-03-29 20:46:45 -05:00
parent b41669cbc6
commit 38daead9b2
12 changed files with 266 additions and 6 deletions
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<IsAotCompatible Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))">true</IsAotCompatible>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Text.Json" Version="10.0.5" />
</ItemGroup>
</Project>
@@ -0,0 +1,56 @@
using System.Text.Json;
namespace StevanFreeborn.Extensions.Configuration.Secure.Storage;
public sealed class JsonFileStorageProvider(JsonStorageOptions options)
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
};
private readonly JsonStorageOptions _options = options
?? throw new ArgumentNullException(nameof(options));
public async Task<string> ReadAsync(string key, CancellationToken ct = default)
{
if (File.Exists(_options.FullPath) is false)
{
return string.Empty;
}
using var stream = new FileStream(_options.FullPath, FileMode.Open, FileAccess.Read);
if (stream.Length is 0)
{
return string.Empty;
}
var data = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, cancellationToken: ct);
if (data is not null && data.TryGetValue(key, out var v))
{
return v;
}
return string.Empty;
}
public async Task WriteAsync(string key, string encryptedData, CancellationToken ct = default)
{
Directory.CreateDirectory(_options.DirectoryPath);
var data = new Dictionary<string, string>
{
[key] = encryptedData
};
using var stream = new FileStream(
_options.FullPath,
FileMode.Create,
FileAccess.Write,
FileShare.None
);
await JsonSerializer.SerializeAsync(stream, data, JsonOptions, ct);
}
}
@@ -0,0 +1,8 @@
namespace StevanFreeborn.Extensions.Configuration.Secure.Storage;
public sealed class JsonStorageOptions
{
public string FileName { get; set; } = string.Empty;
public string DirectoryPath { get; set; } = AppContext.BaseDirectory;
public string FullPath => Path.Combine(DirectoryPath, FileName);
}