-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
1419 lines (1201 loc) · 68.3 KB
/
Program.cs
File metadata and controls
1419 lines (1201 loc) · 68.3 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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) Roland Pihlakas 2025
// roland@simplify.ee
//
// Roland Pihlakas licenses this file to you under the GNU Lesser General Public License, ver 2.1.
// See the LICENSE file for more information.
//
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Collections;
using System.Threading;
using System.Diagnostics;
using System.Security.AccessControl;
namespace DuplicateFileFinder
{
class Program
{
const int SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 0x2;
private const FileAttributes SkipFilesWithAttributes = (
FileAttributes.ReparsePoint
| FileAttributes.Offline
| FileAttributes.Encrypted
//| FileAttributes.Temporary //TODO: option to skip these files
);
//P/Invoke for creating symbolic links on Windows
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CreateSymbolicLink(string lpFileName, string lpExistingFileName, int flags);
private class AllFileAttributes
{
public FileAttributes? Attributes;
public DateTime? CreationTime;
public DateTime? ModificationTime;
public DateTime? AccessTime;
public FileSecurity AccessControl;
}
private static void Main(string[] args)
{
int deletionRetryCount = 10; //TODO: parse from command line or from config file
//Basic argument parsing
//TODO implement logging to file not just to console
//TODO print statistics about freed part size minus shared part size
//TODO implment option to provide arguments via config file
//An optional fourth argument: "try-run" which will skip the actual moving/linking steps.
if (args.Length < 3)
{
Console.WriteLine("A tool that detects duplicate files and replaces them with symlinks to a shared file in a special shared files folder.");
Console.WriteLine("Usage: DuplicateFileFinder.exe <minSizeBytes> <directoryToScan> <sharedDirectory> [<hashCacheRoot>] [try-run]");
Console.WriteLine("Example: DuplicateFileFinder.exe 1000000 C:\\ C:\\___SharedDuplicates C:\\ try-run");
Console.WriteLine("When hashCacheRoot argument is omitted then hash cache is disabled.");
Console.WriteLine("In try-run mode no files will be moved or symlinked, duplicates are only reported in the console.");
return;
}
//Required arguments
if (
!long.TryParse(args[0], out long minSizeBytes)
|| minSizeBytes < 1024 //deduplicating smaller files is meaningless since there will be symbolic link + hash cache file, which each consume at least 512 bytes
)
{
Console.WriteLine("Error: Invalid minimum size (must be at least 1024).");
return;
}
string directoryToScan = Path.GetDirectoryName(args[1]) ?? Directory.GetDirectoryRoot(args[1]); //GetDirectoryName: normalize the path. GetDirectoryRoot: If the path is root folder then GetDirectoryName returns null for some reason.
if (!Directory.Exists(directoryToScan))
{
Console.WriteLine($"Error: Directory '{directoryToScan}' does not exist.");
return;
}
string sharedDirectory = Path.GetDirectoryName(args[2]); //GetDirectoryName: normalize the path
if (sharedDirectory == null)
{
//TODO: allow root folder in case the shared directory is in a different drive than the source drive
//TODO: alternatively check that the shared directory is in a same drive than source directory root
Console.WriteLine($"Error: Shared directory should not be root folder: '{sharedDirectory}'");
return;
}
else if (sharedDirectory.ToUpperInvariant() == directoryToScan.ToUpperInvariant())
{
Console.WriteLine($"Shared directory should not be same as directory to scan");
return;
}
else if (!Directory.Exists(sharedDirectory))
{
Console.WriteLine($"Shared directory '{sharedDirectory}' does not exist. Creating it...");
Directory.CreateDirectory(sharedDirectory);
}
string hashCacheRoot = null;
if (args.Length >= 4 && args[3] != "")
{
hashCacheRoot = Path.GetDirectoryName(args[3]) ?? Directory.GetDirectoryRoot(args[3]); //GetDirectoryName: normalize the path. GetDirectoryRoot: If the path is root folder then GetDirectoryName returns null for some reason.
if (!Directory.Exists(hashCacheRoot))
{
Console.WriteLine($"Hash cache directory '{hashCacheRoot}' does not exist. Creating it...");
Directory.CreateDirectory(hashCacheRoot);
}
}
//make the dir name case-insensitive
//some characters are available only in the upper case
var sharedDirectoryCaseInsensitive = sharedDirectory.ToUpperInvariant();
var hashCacheRootCaseInsensitive = hashCacheRoot?.ToUpperInvariant();
bool hashCacheIsInSameFolderAsFileRoot = (directoryToScan.ToUpperInvariant() == hashCacheRoot?.ToUpperInvariant());
//Optional argument for try-run
bool tryRun = false;
if (args.Length >= 5 && args[4].Equals("try-run", StringComparison.OrdinalIgnoreCase))
{
tryRun = true;
Console.WriteLine("Running in TRY-RUN mode. No files will be moved or symlinked.");
}
Console.WriteLine("Scanning files...");
var files = GetAllFiles(directoryToScan, sharedDirectoryCaseInsensitive, hashCacheRootCaseInsensitive);
Console.WriteLine("Indexing potential duplicates...");
//Data structure:
//filename -> (size -> (hash -> List of file paths))
//var duplicatesIndex = new Dictionary<string, Dictionary<long, Dictionary<string, List<string>>>>(/*StringComparer.OrdinalIgnoreCase*/);
var duplicatesIndex = GetAllExistingSharedFiles(sharedDirectory, minSizeBytes);
long fileIndex = 0;
foreach (var filePath in files)
{
try
{
if (fileIndex % 10000 == 0)
Console.WriteLine($"{fileIndex} files scanned...");
fileIndex++;
FileInfo fi = new FileInfo(filePath);
//Filter by size
if (fi.Length < minSizeBytes)
continue;
string filename = fi.Name;
long size = fi.Length;
//We will lazily compute the hash later (only if we see more than one file with the same name+size).
//TODO: Automatically turn off case insensitivity under Linux
//TODO: command line option to turn off or on case insensitivity manually
var caseInsensitiveFilename = filename.ToUpperInvariant();
//Insert a placeholder in dictionary
if (!duplicatesIndex.TryGetValue(caseInsensitiveFilename, out var sizeDict))
{
sizeDict = new Dictionary<long, Dictionary<string, List<string>>>(); //TODO: Use OrderedDictionary to make hashing and content scanning progress logs more deterministic
duplicatesIndex[caseInsensitiveFilename] = sizeDict;
}
if (!sizeDict.TryGetValue(size, out var hashDict))
{
hashDict = new Dictionary<string, List<string>>(); //TODO: Use OrderedDictionary to make hashing and content scanning progress logs more deterministic
sizeDict[size] = hashDict;
}
string fileHash = ""; //calculate hashes later only for potentially duplicate files
//Insert a placeholder in dictionary
if (!hashDict.TryGetValue(fileHash, out var pathList))
{
pathList = new List<string>();
hashDict[fileHash] = pathList;
}
pathList.Add(filePath);
}
catch (Exception ex)
{
Console.WriteLine($"Error accessing file '{filePath}': {ex.Message}");
}
} //foreach (var targetFilePath in files)
long fileCount = 0;
long totalBytes = 0;
Console.WriteLine("Counting potential duplicates...");
foreach (var filenameEntry in duplicatesIndex)
{
foreach (var sizeEntry in filenameEntry.Value)
{
var hashDict = sizeEntry.Value;
if (!hashDict.TryGetValue("", out var unhashedFileList)) //it might be that hashdict contains only hash of an earlier file in the shared folder
{
hashDict.Clear(); //free a bit of memory: remove hashes of earlier files in the shared dir
continue;
}
//if there is a deduplicated file from an earlier run with same name and size then do not require hash count to be >= 2
//.Count == 1 means the only entry is the uncomputed hash placeholder value of ""
bool haveEarlierSharedFilesWithSameNameAndSize = hashDict.Count > 1;
if (!haveEarlierSharedFilesWithSameNameAndSize)
{
if (unhashedFileList.Count < 2)
{
hashDict.Clear(); //free a bit of memory: remove the "" entry
continue; //not a duplicate set
}
}
else
{
bool qqq = true; //for debugging
}
fileCount += unhashedFileList.Count;
totalBytes += unhashedFileList.Count * sizeEntry.Key;
}
}
Console.WriteLine($"Found {fileCount} potential duplicate files, total {totalBytes} bytes");
var unwritableFolders = new HashSet<string>();
var delayedDeletions = new HashSet<string>();
Console.WriteLine("Computing hashes of potential duplicates...");
fileIndex = 0;
long processedBytes = 0;
long lastProcessedBytes = 0;
foreach (var filenameEntry in duplicatesIndex)
{
foreach (var sizeEntry in filenameEntry.Value)
{
var hashDict = sizeEntry.Value;
if (!hashDict.TryGetValue("", out var unhashedFileList)) //"" entry is removed by above loop when unhashedFileList.Count < 2
continue;
try
{
foreach (var filePath in unhashedFileList)
{
if (fileIndex % 100 == 0)
Console.WriteLine($"{fileIndex} / {fileCount} files hashed...");
if (
processedBytes / ((long)10 * 1000 * 1000 * 1000)
> lastProcessedBytes / ((long)10 * 1000 * 1000 * 1000)
) //bytes will not be exactly divisible in the current loop, therefore cannot use % here
{
lastProcessedBytes = processedBytes;
Console.WriteLine($"{processedBytes} / {totalBytes} bytes hashed...");
}
fileIndex++;
processedBytes += sizeEntry.Key;
Console.WriteLine($"Hashing {filePath}");
//Compute hash
string fileHash = CheckFolderWritabilityAndGetFileHash
(
hashCacheIsInSameFolderAsFileRoot,
filePath,
hashCacheRoot,
unwritableFolders,
delayedDeletions
);
if (fileHash == null) //folder is not writable, therefore no point in processing this file further
continue;
//Insert into the dictionary
if (!hashDict.TryGetValue(fileHash, out var pathList))
{
pathList = new List<string>();
hashDict[fileHash] = pathList;
}
pathList.Add(filePath);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error accessing file group '{filenameEntry.Key}': {ex.Message}");
unhashedFileList.Clear();
}
hashDict.Remove(""); //free a bit of memory
} //foreach (var sizeEntry in filenameEntry.Value)
} //foreach (var filenameEntry in duplicatesIndex)
long fileGroupCount = 0;
fileCount = 0;
totalBytes = 0;
Console.WriteLine("Counting potential duplicates...");
foreach (var filenameEntry in duplicatesIndex)
{
foreach (var sizeEntry in filenameEntry.Value)
{
foreach (var hashEntry in sizeEntry.Value)
{
var fileList = hashEntry.Value;
if (fileList.Count < 2)
{
fileList.Clear(); //free a bit of memory
continue; //not a duplicate set
}
fileGroupCount++;
fileCount += fileList.Count;
totalBytes += fileList.Count * sizeEntry.Key;
}
}
}
Console.WriteLine($"Found {fileCount} potential duplicate files (with same hash) in {fileGroupCount} file groups, total {totalBytes} bytes");
//Now we have a structure of all files grouped by (filename + size + hash).
//For each group with more than 1 file, we consider them POTENTIAL duplicates.
//Lets verify the potential duplicates by reading their content.
Console.WriteLine("Comparing file content of potential duplicates...");
long lastLoggedFileIndex = 0;
long fileGroupIndex = 0;
fileIndex = 0;
processedBytes = 0;
lastProcessedBytes = 0;
foreach (var filenameEntry in duplicatesIndex)
{
foreach (var sizeEntry in filenameEntry.Value)
{
foreach (var hashEntry in sizeEntry.Value)
{
var fileList = hashEntry.Value;
if (fileList.Count < 2)
continue; //not a duplicate set
if (fileGroupIndex % 10 == 0)
Console.WriteLine($"{fileGroupIndex} / {fileGroupCount} file groups compared...");
if (fileIndex / 100 > lastLoggedFileIndex / 100) //file indexes will not be exactly divisible in the current loop, therefore cannot use % here
{
lastLoggedFileIndex = fileIndex;
Console.WriteLine($"{fileIndex} / {fileCount} files compared...");
}
if (
processedBytes / ((long)10 * 1000 * 1000 * 1000)
> lastProcessedBytes / ((long)10 * 1000 * 1000 * 1000)
) //bytes will not be exactly divisible in the current loop, therefore cannot use % here
{
lastProcessedBytes = processedBytes;
Console.WriteLine($"{processedBytes} / {totalBytes} bytes compared...");
}
fileGroupIndex++;
fileIndex += fileList.Count;
processedBytes += fileList.Count * sizeEntry.Key;
Console.WriteLine($"Comparing group {filenameEntry.Key}");
//We have a set of duplicates: same name, same size, same hash
//Lets check the file content
bool equal = true;
List<Tuple<byte[], FileStream>> chunksAndReaders = new List<Tuple<byte[], FileStream>>();
try
{
foreach (var filePath in fileList)
{
var buffer = new byte[1024 * 1024];
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
chunksAndReaders.Add(new Tuple<byte[], FileStream>(buffer, fileStream));
}
FileStream reader0 = chunksAndReaders[0].Item2;
while (
equal
&& reader0.Position < reader0.Length
)
{
for (int i = 0; i < fileList.Count; i++)
{
var buffer = chunksAndReaders[i].Item1;
var fileStream = chunksAndReaders[i].Item2;
int maxBytesToRead = (int)Math.Min(1024 * 1024, sizeEntry.Key - fileStream.Position);
fileStream.Read(buffer, 0/*this is array offset, not file offset*/, maxBytesToRead); //it is okay if the remaining bytes in the buffer are not overwritten, then they will just contain equal bytes from earlier read
}
for (int i = 1; i < fileList.Count; i++)
{
var filePath = fileList[i];
var buffer0 = chunksAndReaders[0].Item1;
var buffer = chunksAndReaders[i].Item1;
if (!buffer0.SequenceEqual(buffer))
{
equal = false;
break;
}
}
}
}
catch (Exception ex)
{
//TODO: exclude only the file that cannot be read from the deduplication
Console.WriteLine($"Error accessing file group '{filenameEntry.Key}': {ex.Message}");
equal = false;
}
foreach (var chunkAndReader in chunksAndReaders)
{
var fileStream = chunkAndReader.Item2;
fileStream.Close();
}
if (!equal)
{
Console.WriteLine("Non-equal files with colliding hashes found!");
fileList.Clear();
}
} //foreach (var hashEntry in sizeEntry.Value)
} //foreach (var sizeEntry in filenameEntry.Value)
} //foreach (var filenameEntry in duplicatesIndex)
fileGroupCount = 0;
fileCount = 0;
totalBytes = 0;
Console.WriteLine("Counting duplicates...");
foreach (var filenameEntry in duplicatesIndex)
{
foreach (var sizeEntry in filenameEntry.Value)
{
foreach (var hashEntry in sizeEntry.Value)
{
var fileList = hashEntry.Value;
if (fileList.Count < 2)
continue; //not a duplicate set
fileGroupCount++;
fileCount += fileList.Count;
totalBytes += fileList.Count * sizeEntry.Key;
}
}
}
Console.WriteLine($"Found {fileCount} duplicate files in {fileGroupCount} file groups, total {totalBytes} bytes");
//Now we have a structure of all files grouped by (filename + size + hash + content).
//For each group with more than 1 file, we consider them duplicates.
//If tryRun = false, we'll:
// 1) Move the first encountered file to the shared directory -> create a symlink in original location.
// 2) For the rest, replace them with a symlink to that same file in the shared directory.
//If tryRun = true, we only print what we WOULD do.
Console.WriteLine("Processing duplicates...");
lastLoggedFileIndex = 0;
fileGroupIndex = 0;
fileIndex = 0;
processedBytes = 0;
lastProcessedBytes = 0;
foreach (var filenameEntry in duplicatesIndex) //TODO: First count number of files to be processed
{
foreach (var sizeEntry in filenameEntry.Value)
{
foreach (var hashEntry in sizeEntry.Value)
{
var hash = hashEntry.Key;
var fileList = hashEntry.Value;
if (fileList.Count < 2)
continue; //not a duplicate set
if (fileGroupIndex % 100 == 0)
Console.WriteLine($"{fileGroupIndex} / {fileGroupCount} file groups symlinked...");
if (fileIndex / 1000 > lastLoggedFileIndex / 1000) //file indexes will not be exactly divisible in the current loop, therefore cannot use % here
{
lastLoggedFileIndex = fileIndex;
Console.WriteLine($"{fileIndex} / {fileCount} files symlinked...");
}
if (
processedBytes / ((long)100 * 1000 * 1000 * 1000)
> lastProcessedBytes / ((long)100 * 1000 * 1000 * 1000)
) //bytes will not be exactly divisible in the current loop, therefore cannot use % here
{
lastProcessedBytes = processedBytes;
Console.WriteLine($"{processedBytes} / {totalBytes} bytes symlinked...");
}
fileGroupIndex++;
fileIndex += fileList.Count;
processedBytes += fileList.Count * sizeEntry.Key;
//We have a set of duplicates: same name, same size, same hash, same content.
//The first becomes the "canonical" copy in the shared folder.
//A symlink will be placed to its original location.
//The rest get replaced with a symlink as well.
string groupName = filenameEntry.Key.ToLowerInvariant();
string canonicalFilename =
Path.GetFileNameWithoutExtension(groupName)
//NB! do not use dot for separating the metadata since that would make extensionless file handling difficult
+ "-" + sizeEntry.Key.ToString() //size in file name is needed to avoid filename collisions
+ "-" + hash
+ Path.GetExtension(groupName);
string newSharedPath = Path.Combine(sharedDirectory, canonicalFilename);
Console.WriteLine($"Symlinking group {filenameEntry.Key} to {canonicalFilename}");
//If we're in tryRun mode, just show the grouping.
#if !READONLY
if (tryRun)
#else
if (true)
#endif
{
string sourceFile0 = fileList[0];
Console.WriteLine();
Console.WriteLine($"[TRY-RUN] Duplicates found (filename='{sourceFile0}', size={sizeEntry.Key}, hash={hashEntry.Key}):");
foreach (var dupPath in fileList)
{
Console.WriteLine($" - {dupPath}");
}
}
else
{
//Normal mode: Move and link
#if !READONLY
//Move the first canonical file if necessary and create links for the rest
for (int i = 0; i < fileList.Count; i++)
{
var duplicatePath = fileList[i];
//TODO: use case-sensitive comparison in Linux and Mac
if (Path.GetDirectoryName(duplicatePath).ToUpperInvariant() == sharedDirectoryCaseInsensitive)
{
Debug.Assert(newSharedPath == duplicatePath);
Debug.Assert(File.Exists(newSharedPath));
//shared file from an earlier run
continue;
}
var allFileAttributes = GetAllFileAttributes(duplicatePath);
//Move canonical file to shared dir if not already moved.
//Has the canonical file been created during earlier runs of the program?
//or during earlier loops of the current file group processing?
if (!File.Exists(newSharedPath))
{
if (i == fileList.Count - 1)
{
//skip further processing in this group if there is only one file left
//to process and we were not able to create the canonical until now
break;
}
try
{
//readonly attribute is not a concern here - moving a readonly file works without issues
File.Move(duplicatePath, newSharedPath);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to move file from '{duplicatePath}' to '{newSharedPath}': {ex.Message}");
//NB! we will still try creating canonical from the other duplicates if there are at least two more remaining.
continue;
}
try
{
//TODO: create symbolic links with same attributes and permissions as the original file
CreateSymbolicLinkOrThrow(duplicatePath, newSharedPath);
Console.WriteLine($"[CANONICAL] {duplicatePath} -> {newSharedPath}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to move/create link for '{duplicatePath}': {ex.Message}");
try
{
//restore file at the original location
//readonly attribute is not a concern here - moving a readonly file works without issues
File.Move(newSharedPath, duplicatePath);
//NB! we will still try creating canonical from the other duplicates if there are at least two more remaining.
continue;
}
catch (Exception ex2)
{
Console.WriteLine($"Major Error: Failed to move file back from '{newSharedPath}' to '{duplicatePath}': {ex2.Message}");
//NB! since the canonical file was created then we can proceed handling the other files
continue;
}
}
//set symbolic link attributes
CopyFileAttributes(duplicatePath, allFileAttributes);
//set shared file attributes
SetSharedFileAttributes(newSharedPath, allFileAttributes.Attributes);
} //if (!File.Exists(newSharedPath))
else //Create links for the rest
{
if (File.Exists(duplicatePath)) //check that the file was not removed during disk scan
{
var tempPath = duplicatePath + "." + Guid.NewGuid().ToString() + ".deduplicator-tmp";
try
{
if (File.Exists(tempPath))
{
Console.WriteLine($"File already exists '{tempPath}'");
continue;
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to test temporary backup file existence '{tempPath}': {ex.Message}");
continue;
}
try
{
//keep the original file around until the symbolic link creation has succeeded
//readonly attribute is not a concern here - moving a readonly file works without issues
File.Move(duplicatePath, tempPath);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to rename file from '{duplicatePath}' to '{tempPath}': {ex.Message}");
continue;
}
try
{
CreateSymbolicLinkOrThrow(duplicatePath, newSharedPath);
Console.WriteLine($"[DUPLICATE] {duplicatePath} linked -> {newSharedPath}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to replace '{duplicatePath}' with symlink: {ex.Message}");
try
{
//restore file at the original location
File.Move(tempPath, duplicatePath);
}
catch (Exception ex2)
{
Console.WriteLine($"Major Error: Failed to rename file back from '{tempPath}' to '{duplicatePath}': {ex2.Message}");
}
continue;
}
//set symbolic link attributes
CopyFileAttributes(duplicatePath, allFileAttributes);
//remove read-only attribute from the temp file, else deletion will fail
//this is documented - https://learn.microsoft.com/en-us/dotnet/api/system.io.file.delete
if (
allFileAttributes.Attributes.HasValue
&& (allFileAttributes.Attributes.Value & FileAttributes.ReadOnly) != 0
)
{
FileAttributes attributes = allFileAttributes.Attributes.Value & ~FileAttributes.ReadOnly;
File.SetAttributes(tempPath, attributes);
}
//try deletion n times, if it still fails then queue for retry after main deduplication loop ends
bool deletionSuccess = false;
for (int deletionRetryIndex = 0; deletionRetryIndex < deletionRetryCount; deletionRetryIndex++)
{
if (deletionRetryIndex > 0)
Thread.Sleep(/*millisecondsTimeout*/1000);
try
{
//remove the original's backup after symbolic link creation succeeded
File.Delete(tempPath);
deletionSuccess = true;
break;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to delete temporary backup file, will retry immediately: '{tempPath}': {ex.Message}");
}
}
if (!deletionSuccess)
{
Console.WriteLine($"Failed to delete temporary backup file, will retry later: '{tempPath}'");
delayedDeletions.Add(tempPath);
}
} //if (File.Exists(targetFilePath))
} //if (!File.Exists(newSharedPath))
} //for (int i = 1; i < unhashedFileList.Count; i++)
#endif
} //if (tryRun)
} //foreach (var hashEntry in sizeEntry.Value)
} //foreach (var sizeEntry in filenameEntry.Value)
} //foreach (var filenameEntry in duplicatesIndex)
Console.WriteLine("Retrying deletion of temporary backup files...");
foreach (var tempPath in delayedDeletions)
{
try
{
//remove the original's backup after symbolic link creation succeeded
File.Delete(tempPath);
}
catch (Exception ex)
{
//TODO option to queue for deletion during reboot
Console.WriteLine($"Failed to delete temporary file '{tempPath}': {ex.Message}");
}
}
Console.WriteLine("Duplicate processing complete. Press any key to quit.");
Console.ReadKey();
} //static void Main(string[] args)
///<summary>
///Gets all files in a directory (recursively), handling exceptions (e.g., unauthorized folders).
///</summary>
private static IEnumerable<string> GetAllFiles(string root, string sharedDirectoryCaseInsensitive, string hashCacheRootCaseInsensitive)
{
var comparer = new CaseInsensitiveComparer();
Queue<string> dirs = new Queue<string>();
dirs.Enqueue(root);
long dirIndex = 0;
while (dirs.Count > 0)
{
string currentDir = dirs.Dequeue();
string[] subDirs = null;
string[] files = null;
try
{
if (dirIndex % 10000 == 0)
Console.WriteLine($"{dirIndex} dirs scanned...");
dirIndex++;
//do not return files that are already symlinks or other special files (OneDrive placeholders, etc.)
var attributes = File.GetAttributes(currentDir); //this method works on directories as well
if ((attributes & SkipFilesWithAttributes) != 0)
{
if ((attributes & FileAttributes.ReparsePoint) != 0)
{
Console.WriteLine($"Skipping directory that is reparse point {currentDir}");
}
else if ((attributes & FileAttributes.Offline) != 0)
{
Console.WriteLine($"Skipping directory that is offline {currentDir}");
}
else if ((attributes & FileAttributes.Encrypted) != 0)
{
Console.WriteLine($"Skipping directory that is encrypted {currentDir}");
}
else if ((attributes & FileAttributes.Temporary) != 0)
{
Console.WriteLine($"Skipping directory that is temporary {currentDir}");
}
else
{
Debug.Assert(false); //skipping a directory for undocumented reason
Console.WriteLine($"Skipping directory {currentDir}");
}
continue;
}
//TODO: implement a method that skips inaccessible entries and still returns the rest of the entries in the same folder
subDirs = Directory.GetDirectories(currentDir);
files = Directory.GetFiles(currentDir);
//TODO: this sorting is not sufficient in the sense that the dirs queue scans breadth-first
Array.Sort(subDirs, comparer);
Array.Sort(files, comparer);
}
catch
{
//Skip folder if we can't access it
Console.WriteLine($"Error accessing directory {currentDir}");
continue;
}
//this code block needs to be outside of try-catch because yield return is not allowed inside try-catch
foreach (string file in files)
{
//TODO option to add folder exclusions which will not be de-duplicated
var extension = Path.GetExtension(file);
if (extension == ".deduplicator-hash")
continue;
else if (extension == ".deduplicator-tmp")
continue;
try
{
//do not return files that are already symlinks or other special files (OneDrive placeholders, etc.)
var attributes = File.GetAttributes(file);
if ((attributes & SkipFilesWithAttributes) != 0)
{
//TODO if the reparse point refers to the deduplication folder,
//then maybe do not skip it so that it can be considered in deduplication logic for the purposs of REMOVING deduplicated files that DO NOT have more than one reference to them?
//TODO: refactor this code into a shared method
if ((attributes & FileAttributes.ReparsePoint) != 0) //a reparse point => possibly a symlink
{
Console.WriteLine($"Skipping file that is reparse point {file}");
}
else if ((attributes & FileAttributes.Offline) != 0)
{
Console.WriteLine($"Skipping file that is offline {file}");
}
else if ((attributes & FileAttributes.Encrypted) != 0)
{
Console.WriteLine($"Skipping file that is encrypted {file}");
}
else if ((attributes & FileAttributes.Temporary) != 0)
{
Console.WriteLine($"Skipping file that is temporary {file}");
}
else
{
Debug.Assert(false); //skipping a file for undocumented reason
Console.WriteLine($"Skipping file {file}");
}
continue;
}
}
catch
{
//skip file if we can't access it
Console.WriteLine($"Error accessing file {file}");
continue;
}
//this needs to be outside of try-catch
yield return file;
} //foreach (string file in files)
foreach (string subDir in subDirs)
{
var subDirCaseInsensitive = subDir.ToUpperInvariant();
//TODO: use case-sensitive comparison in Linux and Mac
if (subDirCaseInsensitive == sharedDirectoryCaseInsensitive)
{
//files in the shared dir will be processed separately
continue;
}
else if (subDirCaseInsensitive == hashCacheRootCaseInsensitive)
{
//NB! If hash cache root is same as deduplication root then it is not skipped
continue;
}
else
{
dirs.Enqueue(subDir);
}
}
} //while (dirs.Count > 0)
} //static IEnumerable<string> GetAllFiles(string root, string sharedDirectoryCaseInsensitive, string hashCacheRootCaseInsensitive)
///<summary>
///Gets all files in the shared directory, handling exceptions (e.g., unauthorized files) and skipping subfolders.
///</summary>
private static Dictionary<string, Dictionary<long, Dictionary<string, List<string>>>> GetAllExistingSharedFiles(string sharedDirectory, long minSizeBytes)
{
Console.WriteLine($"Processing earlier files in the shared directory {sharedDirectory}");
var hashTemplate = GetHashTemplate();
//Data structure:
//filename -> (size -> (hash -> List of file paths))
var sharedFilesIndex = new Dictionary<string, Dictionary<long, Dictionary<string, List<string>>>>(/*StringComparer.OrdinalIgnoreCase*/);
string[] files = Directory.GetFiles(sharedDirectory);
//this code block needs to be outside of try-catch because yield return is not allowed inside try-catch
foreach (string file in files)
{
try
{
//do not return files that are symlinks or other special files (OneDrive placeholders, etc.)
//normally, shared files folder should not contain them,
//but if any such file ends up there then it is definitely not a deduplicated file
var attributes = File.GetAttributes(file);
if ((attributes & SkipFilesWithAttributes) != 0)
{
//TODO: refactor this code into a shared method
if ((attributes & FileAttributes.ReparsePoint) != 0)
{
Console.WriteLine($"Skipping file that is reparse point {file}");
}
else if ((attributes & FileAttributes.Offline) != 0)
{
Console.WriteLine($"Skipping file that is offline {file}");
}
else if ((attributes & FileAttributes.Encrypted) != 0)
{
Console.WriteLine($"Skipping file that is encrypted {file}");
}
else if ((attributes & FileAttributes.Temporary) != 0)
{
Console.WriteLine($"Skipping file that is temporary {file}");
}
else
{
Debug.Assert(false); //skipping a file for undocumented reason
Console.WriteLine($"Skipping file {file}");
}
continue;
}
var filename = Path.GetFileNameWithoutExtension(file);
var extension = Path.GetExtension(file);
var parts = new List<string>(filename.Split('-'));
if (parts.Count >= 3) //TODO: add some special extension to the shared folder files so that they can be distinguished from other filenames containing dashes?
{
if (!long.TryParse(parts[parts.Count - 2], out long size))
{
Console.WriteLine($"Skipping file with invalid size part in the shared folder {file}");
}
else if (size < minSizeBytes)
{
Console.WriteLine($"Skipping shared file smaller than minSizeBytes: {file}");
}
else
{
var fileHash = parts[parts.Count - 1];
if (fileHash.Length != hashTemplate.Length)
{
Console.WriteLine($"Skipping file with invalid hash part in the shared folder {file}");
}
else
{
//sanity check
FileInfo fi = new FileInfo(file);
if (fi.Length != size)
{
Console.WriteLine($"Skipping file with invalid size part in the shared folder {file}");
continue;
}
parts.RemoveAt(parts.Count - 1); //remove hash