-
Notifications
You must be signed in to change notification settings - Fork 696
/
FileUtility.cs
82 lines (73 loc) · 2.14 KB
/
FileUtility.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
73
74
75
76
77
78
79
80
81
82
using System;
using System.IO;
using System.Threading;
namespace NuGet.Common
{
/// <summary>
/// File operation helpers.
/// </summary>
public static class FileUtility
{
public static readonly int MaxTries = 3;
/// <summary>
/// Move a file with retries.
/// </summary>
public static void Move(string sourceFileName, string destFileName)
{
if (sourceFileName == null)
{
throw new ArgumentNullException(nameof(sourceFileName));
}
if (destFileName == null)
{
throw new ArgumentNullException(nameof(destFileName));
}
// Run up to 3 times
for (int i = 0; i < MaxTries; i++)
{
// Ignore exceptions for the first attempts
try
{
File.Move(sourceFileName, destFileName);
break;
}
catch (Exception ex) when ((i < (MaxTries - 1)) && (ex is UnauthorizedAccessException || ex is IOException))
{
Sleep(100);
}
}
}
/// <summary>
/// Delete a file with retries.
/// </summary>
public static void Delete(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
// Run up to 3 times
for (int i = 0; i < MaxTries; i++)
{
// Ignore exceptions for the first attempts
try
{
if (File.Exists(path))
{
File.Delete(path);
}
break;
}
catch (Exception ex) when ((i < (MaxTries - 1)) && (ex is UnauthorizedAccessException || ex is IOException))
{
Sleep(100);
}
}
}
private static void Sleep(int ms)
{
// Sleep sync
Thread.Sleep(ms);
}
}
}