-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppSettings.cs
More file actions
56 lines (47 loc) · 1.63 KB
/
AppSettings.cs
File metadata and controls
56 lines (47 loc) · 1.63 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Security.Cryptography;
namespace PCRemoteControlServer;
public class AppSettings
{
private static readonly string SettingsDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"PCRemoteControlServer");
private static readonly string SettingsPath = Path.Combine(SettingsDir, "settings.json");
public int Port { get; set; } = 8080;
public bool RequireAuth { get; set; } = false;
public string Secret { get; set; } = GenerateSecret();
public void Save()
{
Directory.CreateDirectory(SettingsDir);
var json = JsonSerializer.Serialize(this, AppSettingsContext.Default.AppSettings);
File.WriteAllText(SettingsPath, json);
}
public static AppSettings Load()
{
if (!File.Exists(SettingsPath))
return new AppSettings();
try
{
var json = File.ReadAllText(SettingsPath);
return JsonSerializer.Deserialize(json, AppSettingsContext.Default.AppSettings) ?? new AppSettings();
}
catch
{
return new AppSettings();
}
}
public static string GenerateSecret()
{
return string.Create(6, 0, static (span, _) =>
{
Span<byte> bytes = stackalloc byte[6];
RandomNumberGenerator.Fill(bytes);
for (int i = 0; i < span.Length; i++)
span[i] = (char)('0' + bytes[i] % 10);
});
}
}
[JsonSerializable(typeof(AppSettings))]
internal partial class AppSettingsContext : JsonSerializerContext;