| 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 | // Always return a path with a space in it. |
| 39 | var path = Path.Combine(Path.GetTempPath(), ".WIXTEST " + Path.GetRandomFileName()); |
| 40 | |
| 41 | if (create) |
| 42 | { |
| 43 | Directory.CreateDirectory(path); |
| 44 | } |
| 45 | |
| 46 | this.CleanupPaths.Add(path); |
| 47 | |
| 48 | return path; |
| 49 | } |
| 50 | |
| 51 | |
| 52 | #region // IDisposable |
| 53 | |
| 54 | public void Dispose() |
| 55 | { |
| 56 | this.Dispose(true); |
| 57 | GC.SuppressFinalize(this); |
| 58 | } |
| 59 | |
| 60 | protected virtual void Dispose(bool disposing) |
| 61 | { |
| 62 | if (this.Disposed) |
| 63 | { |
| 64 | return; |
| 65 | } |
| 66 | |
| 67 | if (disposing && !this.Keep) |
| 68 | { |
| 69 | foreach (var path in this.CleanupPaths) |
| 70 | { |
| 71 | try |
| 72 | { |
| 73 | if (File.Exists(path)) |
| 74 | { |
| 75 | File.Delete(path); |
| 76 | } |
| 77 | else if (Directory.Exists(path)) |
| 78 | { |
| 79 | Directory.Delete(path, true); |
| 80 | } |
| 81 | } |
| 82 | catch |
| 83 | { |
| 84 | // Best effort delete, so ignore any failures. |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | this.Disposed = true; |
| 90 | } |
| 91 | |
| 92 | #endregion |
| 93 | } |
| 94 | } |