Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.IO;
using System.Text.Json;

namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
var cfg = Config.Load<MyClass>();
Console.WriteLine(cfg.Text);
cfg.Number++;
Console.WriteLine(cfg.Number);
cfg.Save();
Console.ReadKey();
}

class MyClass : Config
{
public string Text { get; set; } = "Empty";
public int Number { get; set; } = 0;
}
}

public class Config
{
const string DefaultFile = "Config.json";

public void Save(string file = DefaultFile)
{
File.WriteAllText(file, JsonSerializer.Serialize(this, GetType()));
}

public static T Load<T>(string file = DefaultFile)
{
if (File.Exists(file))
return JsonSerializer.Deserialize<T>(File.ReadAllText(file));
else
return Activator.CreateInstance<T>();
}
}
}