@@ -289,9 +289,14 @@ static bool Load(bool directoryExists,
289289 bool isInvalid = false ;
290290 if ( writeFile )
291291 {
292- using var fs = File . Create ( settingsFilePath ) ;
292+ using var ms = new MemoryStream ( ) ;
293293 settings = new ( ) ;
294- settings . Save_____ ( fs ) ;
294+ settings . Save_____ ( ms ) ;
295+ ms . Position = 0 ;
296+ using var fs = File . Create ( settingsFilePath ) ;
297+ ms . CopyTo ( fs ) ;
298+ fs . Flush ( ) ;
299+ fs . SetLength ( fs . Position ) ;
295300 }
296301 else
297302 {
@@ -304,15 +309,20 @@ static bool Load(bool directoryExists,
304309 settings = new ( ) ;
305310 isInvalid = true ;
306311
307- // 尝试将错误的配置保存为 .json.i.bak 防止启动软件当前配置被覆盖
308- var settingsFilePath_i_bak = $ "{ settingsFilePath } .i.bak";
309- try
310- {
311- File . Move ( settingsFilePath , settingsFilePath_i_bak ) ;
312- }
313- catch
312+ // 尝试将错误的配置保存为 .json.load.bak 防止启动软件当前配置被覆盖
313+ if ( ! SettingsExtensions . IsZeroFile ( settingsFilePath ) )
314314 {
315+ var settingsFilePath_load_bak = $ "{ settingsFilePath } .load.bak";
316+ try
317+ {
318+ IOPath . FileIfExistsItDelete ( settingsFilePath_load_bak ) ;
319+ File . Move ( settingsFilePath ,
320+ settingsFilePath_load_bak , true ) ;
321+ }
322+ catch
323+ {
315324
325+ }
316326 }
317327 }
318328 }
@@ -330,6 +340,18 @@ static bool Load(bool directoryExists,
330340
331341internal static class SettingsExtensions
332342{
343+ internal static bool IsZeroFile ( string filePath , bool @catch = true )
344+ {
345+ try
346+ {
347+ return new FileInfo ( filePath ) . Length == 0 ;
348+ }
349+ catch
350+ {
351+ return @catch ;
352+ }
353+ }
354+
333355 /// <summary>
334356 /// 将实例序列化为字符串
335357 /// </summary>
@@ -420,9 +442,12 @@ public static void TrySave_____<TSettings>(IOptionsMonitor<TSettings> optionsMon
420442
421443 try
422444 {
423- var settingsFilePath2 = $ "{ settingsFilePath } .bak";
424- IOPath . FileTryDelete ( settingsFilePath2 ) ;
425- File . Move ( settingsFilePath , settingsFilePath2 ) ;
445+ if ( ! SettingsExtensions . IsZeroFile ( settingsFilePath ) )
446+ {
447+ var settingsFilePath2 = $ "{ settingsFilePath } .save.bak";
448+ IOPath . FileTryDelete ( settingsFilePath2 ) ;
449+ File . Move ( settingsFilePath , settingsFilePath2 , true ) ;
450+ }
426451 }
427452 catch ( Exception ex )
428453 {
0 commit comments