前回の発展として、アプリケーションの諸設定を JSON ファイルに格納するクラスを作成してみます。
手順は同様に、まず DTO (Data Transfer Object) を定義し、保存・読み出しの処理は JsonSerializer に委ねるだけです。
アプリ設定格納クラス
public sealed class AppSettingsStore
{
public sealed class SettingsDto
{
public string Theme { get; set; } = "Light";
public int FontSize { get; set; } = 12;
public bool EnableNotifications { get; set; } = true;
}
private readonly string _settingsPath;
public AppSettingsStore(string appName)
{
var root = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var dir = Path.Combine(root, appName);
Directory.CreateDirectory(dir);
_settingsPath = Path.Combine(dir, "settings.json");
}
public SettingsDto Load()
{
if (!File.Exists(_settingsPath))
{
return new SettingsDto(); // デフォルト値
}
var json = File.ReadAllText(_settingsPath);
return JsonSerializer.Deserialize<SettingsDto>(json) ?? new SettingsDto();
}
public void Save(SettingsDto settings)
{
var json = JsonSerializer.Serialize(settings,
new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(_settingsPath, json);
}
}
テストコード
var appSettingsStore = new AppSettingsStore("SampleJson");
// 1. 初回読み込み(ファイルがない場合はデフォルト値)
Console.WriteLine("\n[1. 初回読み込み]");
var currentSettings = appSettingsStore.Load();
Console.WriteLine($"Theme: {currentSettings.Theme}");
Console.WriteLine($"FontSize: {currentSettings.FontSize}");
Console.WriteLine($"EnableNotifications: {currentSettings.EnableNotifications}");
// 2. 設定を変更
Console.WriteLine("\n[2. 設定を変更]");
currentSettings.Theme = "Dark";
currentSettings.FontSize = 16;
currentSettings.EnableNotifications = false;
Console.WriteLine($"変更後 - Theme: {currentSettings.Theme},
FontSize: {currentSettings.FontSize},
EnableNotifications: {currentSettings.EnableNotifications}"
);
// 3. 保存
Console.WriteLine("\n[3. 保存]");
appSettingsStore.Save(currentSettings);
Console.WriteLine("設定を保存しました。");
// 4. 再読み込みして確認
Console.WriteLine("\n[4. 再読み込みして確認]");
var reloadedSettings = appSettingsStore.Load();
Console.WriteLine($"Theme: {reloadedSettings.Theme}");
Console.WriteLine($"FontSize: {reloadedSettings.FontSize}");
Console.WriteLine($"EnableNotifications: {reloadedSettings.EnableNotifications}");
Console.WriteLine($"保存先: {Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"SampleJson", "settings.json"
)}");
参考サイト
JsonSerializer Class (System.Text.Json) | Microsoft Learn
https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer?view=net-10.0