From 7a96e8cfe3786499e11510d7e41f09db866e4e76 Mon Sep 17 00:00:00 2001 From: Matt Nadareski Date: Wed, 29 Jan 2025 11:06:13 -0500 Subject: [PATCH] Don't crash if writing fails --- ProtectionScan/Program.cs | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/ProtectionScan/Program.cs b/ProtectionScan/Program.cs index 32cf31d5..45967da8 100644 --- a/ProtectionScan/Program.cs +++ b/ProtectionScan/Program.cs @@ -67,8 +67,16 @@ namespace ProtectionScan } catch (Exception ex) { - using var sw = new StreamWriter(File.OpenWrite($"exception-{DateTime.Now:yyyy-MM-dd_HHmmss.ffff}.txt")); - sw.WriteLine(ex); + try + { + using var sw = new StreamWriter(File.OpenWrite($"exception-{DateTime.Now:yyyy-MM-dd_HHmmss.ffff}.txt")); + sw.WriteLine(ex); + } + catch + { + Console.WriteLine("Could not open exception log file for writing. See original message below:"); + Console.WriteLine(ex); + } } } @@ -85,7 +93,17 @@ namespace ProtectionScan return; } - using var sw = new StreamWriter(File.OpenWrite($"protection-{DateTime.Now:yyyy-MM-dd_HHmmss.ffff}.txt")); + // Attempt to open a protection file for writing + StreamWriter? sw = null; + try + { + sw = new StreamWriter(File.OpenWrite($"protection-{DateTime.Now:yyyy-MM-dd_HHmmss.ffff}.txt")); + } + catch + { + Console.WriteLine("Could not open protection log file for writing. Only a console log will be provided."); + } + #if NET20 var keysArr = new string[protections.Keys.Count]; protections.Keys.CopyTo(keysArr, 0); @@ -107,8 +125,11 @@ namespace ProtectionScan #endif string line = $"{key}: {string.Join(", ", fileProtections)}"; Console.WriteLine(line); - sw.WriteLine(line); + sw?.WriteLine(line); } + + // Dispose of the writer + sw?.Dispose(); } ///