-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMain.cs
95 lines (94 loc) · 2.86 KB
/
Main.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
using System;
using System.IO;
using Newtonsoft.Json;
namespace JsonTool
{
/*
public class JsonTool
{
//Example:
public static JsonRw<TestClass> Json;
public static readonly string ConifgPath = "test.json";
public static void InitConfig()
{
var initobj = new TestClass {
Number = 8848,
Text= "HelloWorld!"
};
var json = new JsonRw<TestClass>(ConifgPath , initobj);
Json = json;
}
}
*/
public class JsonRw<T> where T : new()
{
public T ConfigObj { get; private set; }
public string ConfigPath { get; private set; }
public event EventHandler<ErrorEventArgs> OnError;
public event EventHandler<CreatingEvent> OnCreating;
public JsonRw(string path, T initialConfig)//有初始类
{
ConfigPath = Path.Combine(AppContext.BaseDirectory, path);
ConfigObj = initialConfig;
ReadConfig();
}
public JsonRw(string path)//无初始类
{
ConfigPath = Path.Combine(AppContext.BaseDirectory, path);
ConfigObj = new();
ReadConfig();
}
public bool Exists()
{
return File.Exists(ConfigPath);
}
protected virtual void ErrorOccurred(Exception ex)
{
OnError?.Invoke(this,new ErrorEventArgs(ex));
}
protected virtual void CreatingOccurred(string text)
{
OnCreating?.Invoke(this, new CreatingEvent(text));
}
public void ReadConfig()
{
try
{
if (!File.Exists(ConfigPath))
{
CreatingOccurred("未找到初始配置!为您生成默认配置...");
}
else
{
using (StreamReader file = File.OpenText(ConfigPath))
{
JsonSerializer serializer = new JsonSerializer();
ConfigObj = (T)serializer.Deserialize(file, typeof(T));
}
}
WriteConfig();
}
catch(Exception ex)
{
ErrorOccurred(ex);
}
}
public void WriteConfig()
{
FileStream fileStream = new FileStream(ConfigPath, FileMode.Create, FileAccess.Write, FileShare.Write);
string value = JsonConvert.SerializeObject(ConfigObj, Formatting.Indented);
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write(value);
}
}
}
public class CreatingEvent : EventArgs
{
public string Text { get; set; }
public CreatingEvent(string text)
{
Text = text;
}
}
}