summaryrefslogtreecommitdiff
path: root/src/internal/WixBuildTools.TestSupport/DisposableFileSystem.cs
blob: f096db72f83a89849433e7a0dbf1d9fc24a6815a (plain)
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
83
84
85
86
87
88
89
90
91
92
93
// 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.

namespace WixBuildTools.TestSupport
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    public class DisposableFileSystem : IDisposable
    {
        protected bool Disposed { get; private set; }

        private List<string> CleanupPaths { get; } = new List<string>();

        public bool Keep { get; }

        public DisposableFileSystem(bool keep = false)
        {
            this.Keep = keep;
        }

        protected string GetFile(bool create = false)
        {
            var path = Path.GetTempFileName();

            if (!create)
            {
                File.Delete(path);
            }

            this.CleanupPaths.Add(path);

            return path;
        }

        public string GetFolder(bool create = false)
        {
            var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            if (create)
            {
                Directory.CreateDirectory(path);
            }

            this.CleanupPaths.Add(path);

            return path;
        }


        #region // IDisposable

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (this.Disposed)
            {
                return;
            }

            if (disposing && !this.Keep)
            {
                foreach (var path in this.CleanupPaths)
                {
                    try
                    {
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                        else if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }
                    }
                    catch
                    {
                        // Best effort delete, so ignore any failures.
                    }
                }
            }

            this.Disposed = true;
        }

        #endregion
    }
}