Skip to content

Commit 7a96e8c

Browse files
committed
Don't crash if writing fails
1 parent 9fee74f commit 7a96e8c

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

ProtectionScan/Program.cs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,16 @@ private static void GetAndWriteProtections(Scanner scanner, string path)
6767
}
6868
catch (Exception ex)
6969
{
70-
using var sw = new StreamWriter(File.OpenWrite($"exception-{DateTime.Now:yyyy-MM-dd_HHmmss.ffff}.txt"));
71-
sw.WriteLine(ex);
70+
try
71+
{
72+
using var sw = new StreamWriter(File.OpenWrite($"exception-{DateTime.Now:yyyy-MM-dd_HHmmss.ffff}.txt"));
73+
sw.WriteLine(ex);
74+
}
75+
catch
76+
{
77+
Console.WriteLine("Could not open exception log file for writing. See original message below:");
78+
Console.WriteLine(ex);
79+
}
7280
}
7381
}
7482

@@ -85,7 +93,17 @@ private static void WriteProtectionResultFile(string path, ProtectionDictionary?
8593
return;
8694
}
8795

88-
using var sw = new StreamWriter(File.OpenWrite($"protection-{DateTime.Now:yyyy-MM-dd_HHmmss.ffff}.txt"));
96+
// Attempt to open a protection file for writing
97+
StreamWriter? sw = null;
98+
try
99+
{
100+
sw = new StreamWriter(File.OpenWrite($"protection-{DateTime.Now:yyyy-MM-dd_HHmmss.ffff}.txt"));
101+
}
102+
catch
103+
{
104+
Console.WriteLine("Could not open protection log file for writing. Only a console log will be provided.");
105+
}
106+
89107
#if NET20
90108
var keysArr = new string[protections.Keys.Count];
91109
protections.Keys.CopyTo(keysArr, 0);
@@ -107,8 +125,11 @@ private static void WriteProtectionResultFile(string path, ProtectionDictionary?
107125
#endif
108126
string line = $"{key}: {string.Join(", ", fileProtections)}";
109127
Console.WriteLine(line);
110-
sw.WriteLine(line);
128+
sw?.WriteLine(line);
111129
}
130+
131+
// Dispose of the writer
132+
sw?.Dispose();
112133
}
113134

114135
/// <summary>

0 commit comments

Comments
 (0)