JD2022-TU1/main/extern/mklinker/Program.cs

60 lines
2 KiB
C#

using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace mklinker
{
/// <summary>
/// A msbuild friendly application that creates hard link between files.
/// </summary>
class Program
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);
static int Main(string[] args)
{
if (args.Length % 2 != 0)
{
Console.WriteLine("Invalid arguments, please specify [target name] and [source file name] for each hard link to create.");
return -2;
}
for (int i = 0; i < args.Length; i += 2)
{
var toCreate = args[i];
var existing = args[i + 1];
try
{
if (!File.Exists(existing))
{
Console.WriteLine("error: File {0} does not exist", toCreate);
return -3;
}
if (!File.Exists(toCreate))
{
if (!Directory.Exists(Path.GetDirectoryName(toCreate)))
{
Directory.CreateDirectory(Path.GetDirectoryName(toCreate));
}
if (!CreateHardLink(toCreate, existing, new IntPtr()))
{
Console.WriteLine("error: Could not create hard link {0} from {1}", toCreate, existing);
return -4;
}
}
}
catch (Exception ex)
{
Console.WriteLine("error: Unhandled exception creating hard link {0} from {1}. Details {2}", toCreate, existing, ex.Message);
return -5;
}
}
return 0;
}
}
}