-
Notifications
You must be signed in to change notification settings - Fork 0
/
Config.cs
107 lines (99 loc) · 3.83 KB
/
Config.cs
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace AutoVDesktop
{
internal class Config
{
public List<string> Desktops { get; set; } = new List<string>();
public int Delay { get; set; } = 1000;
public bool RestoreDesktop { get; set; } = true;
public bool EnsureRestore { get; set; } = false;
public bool ShowNotifyIcon { get; set; } = true;
public bool DebugMode { get; set; } = false;
public bool StartWithWindows { get; set; } = false;
public readonly string confFileName;
public Config()
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
if (path == null)
{
throw new Exception("无法读取程序运行目录");
}
confFileName = Path.Combine(path, "config.json");
// 检查文件夹名的合法性
foreach (var desktopName in Desktops)
{
Regex regex = new(@"[\/?*:|\\<>]");
if (regex.IsMatch(desktopName))
{
Program.Logger.Debug("非法的文件夹名称: " + desktopName);
MessageBox.Show("非法的文件夹名称: " + desktopName + "\n请修改后重试", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Environment.Exit(0);
}
}
if (Delay < 1)
{
Delay = 1000;
}
}
// 从文件加载配置, 或生成一个初始配置, 返回配置文件是否存在
public bool LoadConfig()
{
var result = File.Exists(confFileName);
if (result)
{
string jsonString = File.ReadAllText(confFileName);
try
{
var c = JsonSerializer.Deserialize<Config>(jsonString);
if (c != null)
{
DebugMode = c.DebugMode;
Delay = c.Delay;
StartWithWindows = c.StartWithWindows;
Desktops = c.Desktops;
EnsureRestore = c.EnsureRestore;
ShowNotifyIcon = c.ShowNotifyIcon;
RestoreDesktop = c.RestoreDesktop;
}
}
catch (Exception ex)
{
MessageBox.Show("配置文件解析失败, 请修正或删除后重试: \n" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(1);
}
}
else
{
// 创建新的配置文件
using (Stream s = File.OpenWrite(confFileName))
{
string nowDesktopDir = Path.GetFileName(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
Desktops.Add(nowDesktopDir);
};
Save();
}
return result;
}
public void Save()
{
using (StreamWriter s = new(confFileName, false, Encoding.UTF8))
{
byte[] jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes<Config>(this);
try
{
s.Write(Regex.Unescape(Encoding.UTF8.GetString(jsonUtf8Bytes)));
}
catch (Exception ex)
{
MessageBox.Show("配置文件写入失败: \n" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
};
}
public override string ToString()
{
return $"{Desktops} {Delay} {RestoreDesktop} {EnsureRestore} {ShowNotifyIcon} {DebugMode}";
}
}
}