From 88f7027ed4bf1580094cb68d46d7bc41777ad5f9 Mon Sep 17 00:00:00 2001 From: Ben Olden-Cooligan Date: Sun, 7 Apr 2024 13:20:01 -0700 Subject: [PATCH] Back up unreadable config file before overwriting --- NAPS2.Lib/Config/Model/FileConfigScope.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/NAPS2.Lib/Config/Model/FileConfigScope.cs b/NAPS2.Lib/Config/Model/FileConfigScope.cs index 4ece67e50..bb5c525b3 100644 --- a/NAPS2.Lib/Config/Model/FileConfigScope.cs +++ b/NAPS2.Lib/Config/Model/FileConfigScope.cs @@ -100,7 +100,8 @@ public class FileConfigScope : ConfigScope catch (Exception) { // Failed to load. Since we're using FileShare.None, it can't be concurrent modification. - // Either the file is newly created, or it was corrupted. In either case we can ignore and overwrite. + // Either the file is newly created, or it was corrupted. In either case we can backup and overwrite. + Backup(stream); } // Merge the cache and our changes into a local copy (so in case of exceptions nothing is changed) copy = new ConfigStorage(); @@ -120,4 +121,19 @@ public class FileConfigScope : ConfigScope Log.ErrorException($"Error writing {_filePath}", ex); } } + + private void Backup(FileStream stream) + { + try + { + using var backupStream = new FileStream(_filePath + ".bak", FileMode.Create); + backupStream.SetLength(0); + stream.Seek(0, SeekOrigin.Begin); + stream.CopyTo(backupStream); + } + catch (Exception) + { + // Ignore, we did our best + } + } } \ No newline at end of file