Skip to content

Commit

Permalink
fixed IOException - directory not empty error when deleting cache folder
Browse files Browse the repository at this point in the history
  • Loading branch information
mammo0 committed Mar 9, 2020
1 parent 007c313 commit f62eb08
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
7 changes: 4 additions & 3 deletions NetworkMiner/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
using System.Reflection;
using System.Diagnostics;
using System.Globalization;

using System.Threading.Tasks;

namespace NetworkMiner {
public static class Program {

Expand All @@ -22,7 +23,7 @@ public static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args) {
static async Task Main(string[] args) {
// first set up the logger
SetupLogger("NetworkMiner");

Expand All @@ -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);
Expand Down
35 changes: 35 additions & 0 deletions SharedUtils/FileUtils.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.IO;
using System.Threading.Tasks;

namespace SharedUtils
{
public static class FileUtils
{
public static async Task<bool> 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;
}
}
}
1 change: 1 addition & 0 deletions SharedUtils/SharedUtils.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
<Compile Include="Pcap\PcapParserFactory.cs" />
<Compile Include="Pcap\PcapStreamReader.cs" />
<Compile Include="Pcap\Tools.cs" />
<Compile Include="FileUtils.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

0 comments on commit f62eb08

Please sign in to comment.