@@ -13,12 +13,17 @@ namespace Flow.Launcher.Infrastructure.Storage
13
13
public class JsonStorage < T > where T : new ( )
14
14
{
15
15
protected T ? Data ;
16
+
16
17
// need a new directory name
17
18
public const string DirectoryName = "Settings" ;
18
19
public const string FileSuffix = ".json" ;
20
+
19
21
protected string FilePath { get ; init ; } = null ! ;
22
+
20
23
private string TempFilePath => $ "{ FilePath } .tmp";
24
+
21
25
private string BackupFilePath => $ "{ FilePath } .bak";
26
+
22
27
protected string DirectoryPath { get ; init ; } = null ! ;
23
28
24
29
@@ -35,7 +40,7 @@ public T Load()
35
40
{
36
41
try
37
42
{
38
- Data = JsonSerializer . Deserialize < T > ( serialized ) ?? TryLoadBackup ( ) ?? LoadDefault ( ) ;
43
+ Data = JsonSerializer . Deserialize < T > ( serialized ) ?? TryLoadBackup ( ) ?? LoadDefault ( ) ;
39
44
}
40
45
catch ( JsonException )
41
46
{
@@ -46,6 +51,7 @@ public T Load()
46
51
{
47
52
Data = TryLoadBackup ( ) ?? LoadDefault ( ) ;
48
53
}
54
+
49
55
return Data . NonNull ( ) ;
50
56
}
51
57
@@ -67,12 +73,19 @@ private T LoadDefault()
67
73
try
68
74
{
69
75
var data = JsonSerializer . Deserialize < T > ( File . ReadAllText ( BackupFilePath ) ) ;
76
+
70
77
if ( data != null )
71
78
{
72
79
Log . Info ( $ "|JsonStorage.Load|Failed to load settings.json, { BackupFilePath } restored successfully") ;
73
- File . Replace ( BackupFilePath , FilePath , null ) ;
80
+
81
+ if ( File . Exists ( FilePath ) )
82
+ File . Replace ( BackupFilePath , FilePath , null ) ;
83
+ else
84
+ File . Move ( BackupFilePath , FilePath ) ;
85
+
74
86
return data ;
75
87
}
88
+
76
89
return default ;
77
90
}
78
91
catch ( JsonException )
@@ -94,14 +107,22 @@ private void BackupOriginFile()
94
107
95
108
public void Save ( )
96
109
{
97
- string serialized = JsonSerializer . Serialize ( Data , new JsonSerializerOptions
98
- {
99
- WriteIndented = true
100
- } ) ;
110
+ string serialized = JsonSerializer . Serialize ( Data ,
111
+ new JsonSerializerOptions
112
+ {
113
+ WriteIndented = true
114
+ } ) ;
101
115
102
116
File . WriteAllText ( TempFilePath , serialized ) ;
103
- File . Replace ( TempFilePath , FilePath , BackupFilePath ) ;
104
- File . Delete ( TempFilePath ) ;
117
+
118
+ if ( ! File . Exists ( FilePath ) )
119
+ {
120
+ File . Move ( TempFilePath , FilePath ) ;
121
+ }
122
+ else
123
+ {
124
+ File . Replace ( TempFilePath , FilePath , BackupFilePath ) ;
125
+ }
105
126
}
106
127
}
107
128
}
0 commit comments