@@ -88,93 +88,5 @@ public void Save()
88
88
}
89
89
}
90
90
91
- public class JsonStrorage < T > where T : new ( )
92
- {
93
- private readonly JsonSerializerOptions _serializerSettings ;
94
- private T _data ;
95
- // need a new directory name
96
- public const string DirectoryName = "Settings" ;
97
- public const string FileSuffix = ".json" ;
98
- public string FilePath { get ; set ; }
99
- public string DirectoryPath { get ; set ; }
100
-
101
-
102
- internal JsonStrorage ( )
103
- {
104
- // use property initialization instead of DefaultValueAttribute
105
- // easier and flexible for default value of object
106
- _serializerSettings = new JsonSerializerOptions
107
- {
108
- IgnoreNullValues = false
109
- } ;
110
- }
111
-
112
- public T Load ( )
113
- {
114
- if ( File . Exists ( FilePath ) )
115
- {
116
- var searlized = File . ReadAllText ( FilePath ) ;
117
- if ( ! string . IsNullOrWhiteSpace ( searlized ) )
118
- {
119
- Deserialize ( searlized ) ;
120
- }
121
- else
122
- {
123
- LoadDefault ( ) ;
124
- }
125
- }
126
- else
127
- {
128
- LoadDefault ( ) ;
129
- }
130
- return _data . NonNull ( ) ;
131
- }
132
-
133
- private void Deserialize ( string searlized )
134
- {
135
- try
136
- {
137
- _data = JsonSerializer . Deserialize < T > ( searlized , _serializerSettings ) ;
138
- }
139
- catch ( JsonException e )
140
- {
141
- LoadDefault ( ) ;
142
- Log . Exception ( $ "|JsonStrorage.Deserialize|Deserialize error for json <{ FilePath } >", e ) ;
143
- }
144
-
145
- if ( _data == null )
146
- {
147
- LoadDefault ( ) ;
148
- }
149
- }
150
-
151
- private void LoadDefault ( )
152
- {
153
- if ( File . Exists ( FilePath ) )
154
- {
155
- BackupOriginFile ( ) ;
156
- }
157
-
158
- _data = new T ( ) ;
159
- Save ( ) ;
160
- }
161
-
162
- private void BackupOriginFile ( )
163
- {
164
- var timestamp = DateTime . Now . ToString ( "yyyy-MM-dd-HH-mm-ss-fffffff" , CultureInfo . CurrentUICulture ) ;
165
- var directory = Path . GetDirectoryName ( FilePath ) . NonNull ( ) ;
166
- var originName = Path . GetFileNameWithoutExtension ( FilePath ) ;
167
- var backupName = $ "{ originName } -{ timestamp } { FileSuffix } ";
168
- var backupPath = Path . Combine ( directory , backupName ) ;
169
- File . Copy ( FilePath , backupPath , true ) ;
170
- // todo give user notification for the backup process
171
- }
172
-
173
- public void Save ( )
174
- {
175
- string serialized = JsonSerializer . Serialize ( _data , new JsonSerializerOptions ( ) { WriteIndented = true } ) ;
176
-
177
- File . WriteAllText ( FilePath , serialized ) ;
178
- }
179
- }
91
+ public class JsonStrorage < T > : JsonStorage < T > where T : new ( ) { }
180
92
}
0 commit comments