This repository was archived by the owner on Sep 23, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
497 lines (440 loc) · 18.7 KB
/
Copy pathProgram.cs
File metadata and controls
497 lines (440 loc) · 18.7 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography;
internal static class Program
{
private const string ProgramName = "RecursiveFileCompare";
private sealed record Options(
string OldRoot,
string NewRoot,
string RelativeRoot,
string? OutputPath);
private sealed record ComparisonResult(
List<string> Changed,
List<string> New,
List<string> Removed,
int IdenticalCount);
private static int Main(string[] args)
{
Console.OutputEncoding = new System.Text.UTF8Encoding(false);
if (args.Length == 0 || (args.Length == 1 && IsHelpArgument(args[0])))
{
PrintHelp();
return 0;
}
if (!TryParseArguments(args, out Options? options, out string? error))
{
PrintError(error!);
return 1;
}
if (!TryResolvePaths(options!, out string? oldPath, out string? newPath, out error))
{
PrintError(error!);
return 1;
}
string? outputPath;
try
{
outputPath = options!.OutputPath is null ? null : Path.GetFullPath(options.OutputPath);
if (outputPath is not null)
{
if (IsWithin(oldPath!, outputPath) || IsWithin(newPath!, outputPath))
throw new ArgumentException("The output file must be outside both comparison directories.");
if (Directory.Exists(outputPath))
throw new ArgumentException("The output path is a directory, not a file.");
if (!Directory.Exists(Path.GetDirectoryName(outputPath)))
throw new ArgumentException("The output directory does not exist.");
// Reject invalid Windows names, including alternate data stream syntax.
if (Path.GetFileName(outputPath).IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
throw new ArgumentException("The output filename contains invalid characters.");
string outputDirectory = ResolveDirectoryIdentity(
Path.GetDirectoryName(outputPath)!);
if (IsWithin(ResolveDirectoryIdentity(oldPath!), outputDirectory) ||
IsWithin(ResolveDirectoryIdentity(newPath!), outputDirectory))
throw new ArgumentException(
"The output file must be outside both comparison directories.");
}
}
catch (Exception ex) when (IsExpectedError(ex))
{
PrintError($"Invalid output path: {ex.Message}");
return 1;
}
try
{
ComparisonResult result = Compare(oldPath!, newPath!);
if (outputPath is not null)
SaveReport(outputPath, BuildReport(result, options!.RelativeRoot));
WriteColoredReport(result, options!.RelativeRoot);
return 0;
}
catch (Exception ex) when (IsExpectedError(ex))
{
PrintError(ex.Message);
return 2;
}
}
private static bool IsExpectedError(Exception ex) =>
ex is IOException or UnauthorizedAccessException or ArgumentException or
NotSupportedException or System.Security.SecurityException;
private static bool TryParseArguments(
string[] args, out Options? options, out string? error)
{
options = null;
error = null;
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var positional = new List<string>();
for (int i = 0; i < args.Length; i++)
{
string argument = args[i];
if (!argument.StartsWith("--", StringComparison.Ordinal))
{
positional.Add(argument);
continue;
}
int separator = argument.IndexOf('=');
string name = (separator < 0 ? argument : argument[..separator]).ToLowerInvariant();
if (name is not ("--old" or "--new" or "--relative" or "--output"))
{
error = $"Unknown argument: {name}";
return false;
}
string value;
if (separator >= 0)
value = argument[(separator + 1)..];
else
{
if (++i >= args.Length || args[i].StartsWith("--", StringComparison.Ordinal))
{
error = $"Missing value for {name}.";
return false;
}
value = args[i];
}
if (name != "--relative" && string.IsNullOrWhiteSpace(value))
{
error = $"The value for {name} cannot be empty.";
return false;
}
if (!values.TryAdd(name, value))
{
error = $"Argument specified more than once: {name}";
return false;
}
}
bool namedPaths = values.ContainsKey("--old") || values.ContainsKey("--new") ||
values.ContainsKey("--relative");
string oldRoot, newRoot, relativeRoot;
if (namedPaths)
{
if (positional.Count != 0)
{
error = "Named path arguments cannot be mixed with positional paths.";
return false;
}
if (!values.ContainsKey("--old") || !values.ContainsKey("--new"))
{
error = "Named-argument mode requires both --old and --new.";
return false;
}
oldRoot = values["--old"];
newRoot = values["--new"];
relativeRoot = values.GetValueOrDefault("--relative", string.Empty);
}
else
{
if (positional.Count is < 2 or > 3)
{
error = "Positional mode requires <old-path> <new-path> and optionally [relative-root].";
return false;
}
oldRoot = positional[0];
newRoot = positional[1];
relativeRoot = positional.Count == 3 ? positional[2] : string.Empty;
if (string.IsNullOrWhiteSpace(oldRoot) || string.IsNullOrWhiteSpace(newRoot))
{
error = "The old and new paths cannot be empty.";
return false;
}
}
options = new Options(oldRoot, newRoot, relativeRoot, values.GetValueOrDefault("--output"));
return true;
}
private static bool TryResolvePaths(
Options options,
out string? oldPath,
out string? newPath,
out string? error)
{
oldPath = null;
newPath = null;
error = null;
try
{
string oldRoot = Path.GetFullPath(options.OldRoot);
string newRoot = Path.GetFullPath(options.NewRoot);
if (!Directory.Exists(oldRoot))
{
error = $"The old path does not exist or is not a directory:{Environment.NewLine} {oldRoot}";
return false;
}
if (!Directory.Exists(newRoot))
{
error = $"The new path does not exist or is not a directory:{Environment.NewLine} {newRoot}";
return false;
}
oldPath = ResolveRelativeRoot(oldRoot, options.RelativeRoot);
newPath = ResolveRelativeRoot(newRoot, options.RelativeRoot);
if (!Directory.Exists(oldPath))
{
error = $"The old comparison path does not exist:{Environment.NewLine} {oldPath}";
return false;
}
if (!Directory.Exists(newPath))
{
error = $"The new comparison path does not exist:{Environment.NewLine} {newPath}";
return false;
}
return true;
}
catch (Exception ex) when (IsExpectedError(ex))
{
error = $"Invalid path: {ex.Message}";
return false;
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode,
ExactSpelling = true, SetLastError = true)]
private static extern SafeFileHandle CreateFileW(
string name, uint access, uint share, IntPtr security,
uint disposition, uint flags, IntPtr template);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode,
ExactSpelling = true, SetLastError = true)]
private static extern uint GetFinalPathNameByHandleW(
SafeFileHandle handle, StringBuilder path, uint capacity, uint flags);
private static string ResolveDirectoryIdentity(string path)
{
string fullPath = Path.GetFullPath(path);
if (!fullPath.StartsWith(@"\\?\", StringComparison.Ordinal))
fullPath = fullPath.StartsWith(@"\\", StringComparison.Ordinal)
? @"\\?\UNC\" + fullPath[2..]
: @"\\?\" + fullPath;
// Open an existing directory for metadata, allowing normal sharing.
using SafeFileHandle handle = CreateFileW(
fullPath, 0, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero);
if (handle.IsInvalid)
throw new IOException(
$"Cannot resolve directory '{path}' (Windows error {Marshal.GetLastWin32Error()}).");
var buffer = new StringBuilder(32768);
// Normalized NT device paths avoid differences in local drive aliases.
uint length = GetFinalPathNameByHandleW(
handle, buffer, (uint)buffer.Capacity, 2);
if (length == 0)
throw new IOException(
$"Cannot resolve directory '{path}' (Windows error {Marshal.GetLastWin32Error()}).");
if (length >= buffer.Capacity)
throw new IOException($"Resolved directory path is too long: '{path}'.");
return buffer.ToString();
}
private static string ResolveRelativeRoot(string root, string relativeRoot)
{
if (string.IsNullOrWhiteSpace(relativeRoot))
return root;
if (Path.IsPathRooted(relativeRoot))
throw new ArgumentException("The relative root must be a relative path.");
string resolved = Path.GetFullPath(Path.Combine(root, relativeRoot));
if (!IsWithin(root, resolved))
throw new ArgumentException("The relative root cannot point outside the root directory.");
return resolved;
}
private static bool IsWithin(string root, string path)
{
root = Path.TrimEndingDirectorySeparator(root);
path = Path.TrimEndingDirectorySeparator(path);
string prefix = Path.EndsInDirectorySeparator(root) ? root : root + Path.DirectorySeparatorChar;
return path.Equals(root, StringComparison.OrdinalIgnoreCase) ||
path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
}
private static void SaveReport(string outputPath, string report)
{
// Replace rather than truncate an existing file (including a hard link).
string temporary = Path.Combine(Path.GetDirectoryName(outputPath)!,
$".rfc-{Guid.NewGuid():N}.tmp");
try
{
using (var writer = new StreamWriter(new FileStream(temporary, FileMode.CreateNew,
FileAccess.Write, FileShare.None), new System.Text.UTF8Encoding(false)))
writer.Write(report);
File.Move(temporary, outputPath, overwrite: true);
}
finally
{
try { File.Delete(temporary); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
}
private static ComparisonResult Compare(string oldPath, string newPath)
{
Dictionary<string, byte[]> oldFiles = HashFiles(oldPath);
Dictionary<string, byte[]> newFiles = HashFiles(newPath);
var changed = new List<string>();
var added = new List<string>();
var removed = new List<string>();
int identical = 0;
var allPaths = new SortedSet<string>(oldFiles.Keys, StringComparer.OrdinalIgnoreCase);
allPaths.UnionWith(newFiles.Keys);
foreach (string path in allPaths)
{
bool hasOld = oldFiles.TryGetValue(path, out byte[]? oldHash);
bool hasNew = newFiles.TryGetValue(path, out byte[]? newHash);
if (!hasOld)
added.Add(path);
else if (!hasNew)
removed.Add(path);
else if (!oldHash!.AsSpan().SequenceEqual(newHash))
changed.Add(path);
else
identical++;
}
return new ComparisonResult(changed, added, removed, identical);
}
private static Dictionary<string, byte[]> HashFiles(string root)
{
var files = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);
foreach (string fullPath in EnumerateFiles(root))
{
string relativePath = Path.GetRelativePath(root, fullPath);
try
{
using FileStream stream = File.OpenRead(fullPath);
if (!files.TryAdd(relativePath, SHA256.HashData(stream)))
throw new IOException($"Multiple filenames differ only by case: {fullPath}");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
throw new IOException($"Cannot hash '{fullPath}': {ex.Message}", ex);
}
}
return files;
}
private static IEnumerable<string> EnumerateFiles(string root)
{
var pending = new Stack<string>();
pending.Push(root);
while (pending.Count != 0)
{
var directory = new DirectoryInfo(pending.Pop());
// Include hidden/system files and fail on inaccessible entries.
foreach (FileSystemInfo entry in directory.EnumerateFileSystemInfos())
{
if ((entry.Attributes & FileAttributes.Directory) == 0)
yield return entry.FullName;
else if ((entry.Attributes & FileAttributes.ReparsePoint) == 0)
pending.Push(entry.FullName);
// Do not recurse through directory links/junctions (possible cycles).
}
}
}
private static string BuildReport(ComparisonResult result, string relativeRoot)
{
var lines = new List<string>();
AppendReport(lines, result, relativeRoot);
return string.Join("\r\n", lines) + "\r\n";
}
private static void AppendReport(
List<string> lines,
ComparisonResult result,
string relativeRoot)
{
lines.Add(string.Empty);
lines.Add("===== FILE COMPARISON =====");
lines.Add(string.Empty);
lines.Add($"Changed files: {result.Changed.Count}");
lines.AddRange(result.Changed.Select(path => $" {DisplayPath(relativeRoot, path)}"));
lines.Add(string.Empty);
lines.Add($"New files: {result.New.Count}");
lines.AddRange(result.New.Select(path => $" {DisplayPath(relativeRoot, path)}"));
lines.Add(string.Empty);
lines.Add($"Removed files: {result.Removed.Count}");
lines.AddRange(result.Removed.Select(path => $" {DisplayPath(relativeRoot, path)}"));
lines.Add(string.Empty);
lines.Add($"Identical files: {result.IdenticalCount}");
}
private static void WriteColoredReport(ComparisonResult result, string relativeRoot)
{
Console.WriteLine();
WriteColorLine("===== FILE COMPARISON =====", ConsoleColor.Cyan);
Console.WriteLine();
WriteColorLine($"Changed files: {result.Changed.Count}", ConsoleColor.Yellow);
foreach (string path in result.Changed)
Console.WriteLine($" {DisplayPath(relativeRoot, path)}");
Console.WriteLine();
WriteColorLine($"New files: {result.New.Count}", ConsoleColor.Green);
foreach (string path in result.New)
Console.WriteLine($" {DisplayPath(relativeRoot, path)}");
Console.WriteLine();
WriteColorLine($"Removed files: {result.Removed.Count}", ConsoleColor.Red);
foreach (string path in result.Removed)
Console.WriteLine($" {DisplayPath(relativeRoot, path)}");
Console.WriteLine();
WriteColorLine($"Identical files: {result.IdenticalCount}", ConsoleColor.Gray);
}
private static string DisplayPath(string relativeRoot, string path)
{
if (string.IsNullOrWhiteSpace(relativeRoot))
return path;
string normalizedRoot = relativeRoot
.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
return Path.Combine(normalizedRoot, path);
}
private static void PrintHelp(TextWriter? writer = null)
{
(writer ?? Console.Out).WriteLine($$"""
Recursive File Compare
Recursively compares every file in two directories using SHA-256 hashes.
Usage:
{{ProgramName}}.exe <old-path> <new-path> [relative-root] [--output <file>]
{{ProgramName}}.exe --old <old-path> --new <new-path> [--relative <path>] [--output <file>]
Arguments:
old-path Original or earlier directory.
new-path New or current directory.
relative-root Optional subdirectory to compare beneath both roots.
--output Also save the plain-text report.
Named arguments may use either "--name value" or "--name=value" syntax.
Examples:
{{ProgramName}}.exe "C:\path\old" "C:\path\new"
{{ProgramName}}.exe "C:\path\old" "C:\path\new" "subdirectory"
{{ProgramName}}.exe --old "C:\path\old" --new "C:\path\new" --relative "subdirectory"
{{ProgramName}}.exe "C:\path\old" "C:\path\new" --output "comparison.txt"
""");
}
private static void PrintError(string message)
{
WriteColorLine($"ERROR: {message}", ConsoleColor.Red, error: true);
Console.Error.WriteLine();
PrintHelp(Console.Error);
}
private static void WriteColorLine(string text, ConsoleColor color, bool error = false)
{
TextWriter writer = error ? Console.Error : Console.Out;
if (error ? Console.IsErrorRedirected : Console.IsOutputRedirected)
{
writer.WriteLine(text);
return;
}
ConsoleColor original = Console.ForegroundColor;
try
{
Console.ForegroundColor = color;
writer.WriteLine(text);
}
finally { Console.ForegroundColor = original; }
}
private static bool IsHelpArgument(string argument) =>
argument.Equals("--help", StringComparison.OrdinalIgnoreCase) ||
argument.Equals("-h", StringComparison.OrdinalIgnoreCase) ||
argument.Equals("/?", StringComparison.OrdinalIgnoreCase);
}