From f62eb08c4edfc58137c22c14228e6cdf3ee1d70f Mon Sep 17 00:00:00 2001 From: mammo0 Date: Mon, 9 Mar 2020 09:22:40 +0100 Subject: [PATCH] fixed IOException - directory not empty error when deleting cache folder --- NetworkMiner/Program.cs | 7 ++++--- SharedUtils/FileUtils.cs | 35 ++++++++++++++++++++++++++++++++++ SharedUtils/SharedUtils.csproj | 1 + 3 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 SharedUtils/FileUtils.cs diff --git a/NetworkMiner/Program.cs b/NetworkMiner/Program.cs index 4b00903..cdc1fd1 100644 --- a/NetworkMiner/Program.cs +++ b/NetworkMiner/Program.cs @@ -13,7 +13,8 @@ using System.Reflection; using System.Diagnostics; using System.Globalization; - +using System.Threading.Tasks; + namespace NetworkMiner { public static class Program { @@ -22,7 +23,7 @@ public static class Program { /// /// The main entry point for the application. /// - static void Main(string[] args) { + static async Task Main(string[] args) { // first set up the logger SetupLogger("NetworkMiner"); @@ -49,7 +50,7 @@ static void Main(string[] args) { // remove the cache directory again - Directory.Delete(cacheDirectory, true); + await FileUtils.DeleteDirectory(cacheDirectory); // don't know why the application doesn't exit automatically after reaching the end of the main method... System.Environment.Exit(0); diff --git a/SharedUtils/FileUtils.cs b/SharedUtils/FileUtils.cs new file mode 100644 index 0000000..a9db2ef --- /dev/null +++ b/SharedUtils/FileUtils.cs @@ -0,0 +1,35 @@ +using System; +using System.IO; +using System.Threading.Tasks; + +namespace SharedUtils +{ + public static class FileUtils + { + public static async Task DeleteDirectory(string directoryPath, int maxRetries = 10, int millisecondsDelay = 30) + { + if (directoryPath == null) + throw new ArgumentNullException(directoryPath); + if (maxRetries < 1) + throw new ArgumentOutOfRangeException(nameof(maxRetries)); + if (millisecondsDelay < 1) + throw new ArgumentOutOfRangeException(nameof(millisecondsDelay)); + + for (int i = 0; i < maxRetries; ++i) { + try { + // try to delete the directory if it exists + if (Directory.Exists(directoryPath)) + Directory.Delete(directoryPath, true); + + return true; + } catch (IOException) { // System.IO.IOException: The directory is not empty + await Task.Delay(millisecondsDelay); + } catch (UnauthorizedAccessException) { + await Task.Delay(millisecondsDelay); + } + } + + return false; + } + } +} diff --git a/SharedUtils/SharedUtils.csproj b/SharedUtils/SharedUtils.csproj index 0e6356a..75c13c8 100644 --- a/SharedUtils/SharedUtils.csproj +++ b/SharedUtils/SharedUtils.csproj @@ -52,6 +52,7 @@ + \ No newline at end of file