Skip to content

Commit

Permalink
Don't crash if writing fails
Browse files Browse the repository at this point in the history
  • Loading branch information
mnadareski committed Jan 29, 2025
1 parent 9fee74f commit 7a96e8c
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions ProtectionScan/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,16 @@ private static void GetAndWriteProtections(Scanner scanner, string path)
}
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);
}
}
}

Expand All @@ -85,7 +93,17 @@ private static void WriteProtectionResultFile(string path, ProtectionDictionary?
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);
Expand All @@ -107,8 +125,11 @@ private static void WriteProtectionResultFile(string path, ProtectionDictionary?
#endif
string line = $"{key}: {string.Join(", ", fileProtections)}";
Console.WriteLine(line);
sw.WriteLine(line);
sw?.WriteLine(line);
}

// Dispose of the writer
sw?.Dispose();
}

/// <summary>
Expand Down

0 comments on commit 7a96e8c

Please sign in to comment.