aboutsummaryrefslogtreecommitdiff
path: root/src/WixToolset.Core/Bind/FileSystem.cs
blob: bdd65503409dd2917c79782f55c525600eeaa63b (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
// 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 WixToolset.Core.Bind
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.InteropServices;
    using WixToolset.Extensibility;

    internal class FileSystem
    {
        public FileSystem(IEnumerable<ILayoutExtension> extensions)
        {
            this.Extensions = extensions ?? Array.Empty<ILayoutExtension>();
        }

        private IEnumerable<ILayoutExtension> Extensions { get; }

        /// <summary>
        /// Copies a file.
        /// </summary>
        /// <param name="source">The file to copy.</param>
        /// <param name="destination">The destination file.</param>
        public bool CopyFile(string source, string destination)
        {
            foreach (var extension in this.Extensions)
            {
                if (extension.CopyFile(source, destination))
                {
                    return true;
                }
            }

            if (File.Exists(destination))
            {
                File.Delete(destination);
            }

            if (!CreateHardLink(destination, source, IntPtr.Zero))
            {
#if DEBUG
                int er = Marshal.GetLastWin32Error();
#endif

                File.Copy(source, destination, true);
            }

            return true;
        }

        /// <summary>
        /// Moves a file.
        /// </summary>
        /// <param name="source">The file to move.</param>
        /// <param name="destination">The destination file.</param>
        public bool MoveFile(string source, string destination)
        {
            foreach (var extension in this.Extensions)
            {
                if (extension.MoveFile(source, destination))
                {
                    return true;
                }
            }

            if (File.Exists(destination))
            {
                File.Delete(destination);
            }

            var directory = Path.GetDirectoryName(destination);
            if (!String.IsNullOrEmpty(directory))
            {
                Directory.CreateDirectory(directory);
            }

            File.Move(source, destination);

            return true;
        }

        [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);
    }
}