@@ -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,15 @@ 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
80
File . Replace ( BackupFilePath , FilePath , null ) ;
81
+
74
82
return data ;
75
83
}
84
+
76
85
return default ;
77
86
}
78
87
catch ( JsonException )
@@ -94,14 +103,22 @@ private void BackupOriginFile()
94
103
95
104
public void Save ( )
96
105
{
97
- string serialized = JsonSerializer . Serialize ( Data , new JsonSerializerOptions
98
- {
99
- WriteIndented = true
100
- } ) ;
106
+ string serialized = JsonSerializer . Serialize ( Data ,
107
+ new JsonSerializerOptions
108
+ {
109
+ WriteIndented = true
110
+ } ) ;
101
111
102
112
File . WriteAllText ( TempFilePath , serialized ) ;
103
- File . Replace ( TempFilePath , FilePath , BackupFilePath ) ;
104
- File . Delete ( TempFilePath ) ;
113
+
114
+ if ( ! File . Exists ( FilePath ) )
115
+ {
116
+ File . Move ( TempFilePath , FilePath ) ;
117
+ }
118
+ else
119
+ {
120
+ File . Replace ( TempFilePath , FilePath , BackupFilePath ) ;
121
+ }
105
122
}
106
123
}
107
124
}
0 commit comments