diff options
Diffstat (limited to 'src/internal/WixInternal.TestSupport/DisposableFileSystem.cs')
-rw-r--r-- | src/internal/WixInternal.TestSupport/DisposableFileSystem.cs | 93 |
1 files changed, 93 insertions, 0 deletions
diff --git a/src/internal/WixInternal.TestSupport/DisposableFileSystem.cs b/src/internal/WixInternal.TestSupport/DisposableFileSystem.cs new file mode 100644 index 00000000..b03bbaa4 --- /dev/null +++ b/src/internal/WixInternal.TestSupport/DisposableFileSystem.cs | |||
@@ -0,0 +1,93 @@ | |||
1 | // Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. | ||
2 | |||
3 | namespace WixInternal.TestSupport | ||
4 | { | ||
5 | using System; | ||
6 | using System.Collections.Generic; | ||
7 | using System.IO; | ||
8 | |||
9 | public class DisposableFileSystem : IDisposable | ||
10 | { | ||
11 | protected bool Disposed { get; private set; } | ||
12 | |||
13 | private List<string> CleanupPaths { get; } = new List<string>(); | ||
14 | |||
15 | public bool Keep { get; } | ||
16 | |||
17 | public DisposableFileSystem(bool keep = false) | ||
18 | { | ||
19 | this.Keep = keep; | ||
20 | } | ||
21 | |||
22 | protected string GetFile(bool create = false) | ||
23 | { | ||
24 | var path = Path.GetTempFileName(); | ||
25 | |||
26 | if (!create) | ||
27 | { | ||
28 | File.Delete(path); | ||
29 | } | ||
30 | |||
31 | this.CleanupPaths.Add(path); | ||
32 | |||
33 | return path; | ||
34 | } | ||
35 | |||
36 | public string GetFolder(bool create = false) | ||
37 | { | ||
38 | var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); | ||
39 | |||
40 | if (create) | ||
41 | { | ||
42 | Directory.CreateDirectory(path); | ||
43 | } | ||
44 | |||
45 | this.CleanupPaths.Add(path); | ||
46 | |||
47 | return path; | ||
48 | } | ||
49 | |||
50 | |||
51 | #region // IDisposable | ||
52 | |||
53 | public void Dispose() | ||
54 | { | ||
55 | this.Dispose(true); | ||
56 | GC.SuppressFinalize(this); | ||
57 | } | ||
58 | |||
59 | protected virtual void Dispose(bool disposing) | ||
60 | { | ||
61 | if (this.Disposed) | ||
62 | { | ||
63 | return; | ||
64 | } | ||
65 | |||
66 | if (disposing && !this.Keep) | ||
67 | { | ||
68 | foreach (var path in this.CleanupPaths) | ||
69 | { | ||
70 | try | ||
71 | { | ||
72 | if (File.Exists(path)) | ||
73 | { | ||
74 | File.Delete(path); | ||
75 | } | ||
76 | else if (Directory.Exists(path)) | ||
77 | { | ||
78 | Directory.Delete(path, true); | ||
79 | } | ||
80 | } | ||
81 | catch | ||
82 | { | ||
83 | // Best effort delete, so ignore any failures. | ||
84 | } | ||
85 | } | ||
86 | } | ||
87 | |||
88 | this.Disposed = true; | ||
89 | } | ||
90 | |||
91 | #endregion | ||
92 | } | ||
93 | } | ||