-
-
Notifications
You must be signed in to change notification settings - Fork 290
/
Utility.cs
72 lines (63 loc) · 1.94 KB
/
Utility.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive.Disposables;
using System.Text;
using System.Threading;
using Akavache;
namespace Akavache.Tests
{
static class Utility
{
public static void DeleteDirectory(string directoryPath)
{
// From http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true/329502#329502
var di = new DirectoryInfo(directoryPath);
var files = di.EnumerateFiles();
var dirs = di.EnumerateDirectories();
foreach (var file in files)
{
File.SetAttributes(file.FullName, FileAttributes.Normal);
(new Action(() => file.Delete())).Retry();
}
foreach (var dir in dirs)
{
DeleteDirectory(di.FullName);
}
File.SetAttributes(directoryPath, FileAttributes.Normal);
Directory.Delete(directoryPath, false);
}
public static IDisposable WithEmptyDirectory(out string directoryPath)
{
var di = new DirectoryInfo(Path.Combine(".", Guid.NewGuid().ToString()));
if (di.Exists)
{
DeleteDirectory(di.FullName);
}
di.Create();
directoryPath = di.FullName;
return Disposable.Create(() => DeleteDirectory(di.FullName));
}
public static void Retry(this Action block, int retries = 2)
{
while (true)
{
try
{
block();
return;
}
catch (Exception)
{
if (retries == 0)
{
throw;
}
retries--;
Thread.Sleep(10);
}
}
}
}
}