-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
927 lines (793 loc) · 29.1 KB
/
Form1.cs
File metadata and controls
927 lines (793 loc) · 29.1 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
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
namespace FolderSizeScanner;
public partial class Form1 : Form
{
private const int HardRecursionLimit = 200;
private const int ParallelDepthLimit = 1; // parallelize depth 0 and 1
private CancellationTokenSource? _cts;
private int _maxDepth = 3;
private int _skippedCount;
private FolderInfo? _scanRoot;
private bool _scanRunning;
private System.Windows.Forms.Timer? _uiTimer;
private System.Windows.Forms.Timer? _animTimer;
private long _filesScanned;
private long _foldersScanned;
private string _currentPath = "";
private TreeNode? _subScanNode;
// Win32 P/Invoke
private const int MAX_PATH = 260;
private const int MAX_ALTERNATE = 14;
private const uint FILE_ATTRIBUTE_DIRECTORY = 0x10;
private const uint FILE_ATTRIBUTE_REPARSE_POINT = 0x400;
private static readonly IntPtr INVALID_HANDLE_VALUE = new(-1);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct WIN32_FIND_DATA
{
public uint dwFileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_ALTERNATE)]
public string cAlternateFileName;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr FindFirstFileW(string lpFileName, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool FindNextFileW(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FindClose(IntPtr hFindFile);
public Form1()
{
InitializeComponent();
LoadLogo();
}
private void LoadLogo()
{
var logoPath = Path.Combine(AppContext.BaseDirectory, "P9.png");
if (!File.Exists(logoPath)) return;
try
{
var bmp = new Bitmap(logoPath);
picLogo.Image = bmp;
// Set form icon from the same PNG
var iconBmp = new Bitmap(bmp, 32, 32);
var hIcon = iconBmp.GetHicon();
Icon = Icon.FromHandle(hIcon);
}
catch { }
}
private void BtnBrowse_Click(object sender, EventArgs e)
{
using var dialog = new FolderBrowserDialog
{
Description = "Select a folder to scan",
UseDescriptionForTitle = true
};
if (dialog.ShowDialog() == DialogResult.OK)
{
txtPath.Text = dialog.SelectedPath;
}
}
private void BtnScan_Click(object sender, EventArgs e)
{
if (_scanRunning)
{
_cts?.Cancel();
btnScan.Enabled = false;
lblStatus.Text = "Cancelling...";
return;
}
var path = txtPath.Text.Trim();
if (!Directory.Exists(path))
{
MessageBox.Show("Please select a valid folder.", "Invalid Path",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
_maxDepth = (int)nudDepth.Value;
treeResults.Nodes.Clear();
progressBar.Value = 0;
progressBar.IsMarquee = true;
lblStatus.Text = "Scanning...";
btnScan.Text = "Cancel";
btnScan.IsPrimary = false;
btnBrowse.Enabled = false;
btnExport.Enabled = false;
nudDepth.Enabled = false;
_skippedCount = 0;
_filesScanned = 0;
_foldersScanned = 0;
_currentPath = "";
_scanRoot = null;
_cts = new CancellationTokenSource();
_scanRunning = true;
// Create root node immediately (collapsed)
var rootNode = new TreeNode(Path.GetFileName(path) is { Length: > 0 } name ? name : path)
{
Tag = path
};
treeResults.Nodes.Add(rootNode);
// Start UI update timer
_uiTimer = new System.Windows.Forms.Timer { Interval = 200 };
_uiTimer.Tick += UiTimer_Tick;
_uiTimer.Start();
// Start animation timer for progress bar shimmer
_animTimer = new System.Windows.Forms.Timer { Interval = 16 };
_animTimer.Tick += (_, _) => progressBar.AdvanceAnimation();
_animTimer.Start();
// Launch scan on background thread
var ct = _cts.Token;
Task.Run(() =>
{
try
{
var result = ScanFolder(path, 0, ct);
_scanRoot = result;
}
catch (OperationCanceledException)
{
// _scanRoot may have partial data from children added during scan
}
catch (Exception ex)
{
BeginInvoke(() =>
{
StopTimers();
ResetUiAfterScan();
lblStatus.Text = "Scan failed.";
MessageBox.Show($"{ex.GetType().Name}: {ex.Message}\n\n{ex.StackTrace}",
"Scan Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
});
return;
}
BeginInvoke(OnScanComplete);
}, ct);
}
private void UiTimer_Tick(object? sender, EventArgs e)
{
var files = Interlocked.Read(ref _filesScanned);
var folders = Interlocked.Read(ref _foldersScanned);
var skipped = _skippedCount;
var path = _currentPath;
var display = path.Length > 100
? path[..45] + "..." + path[^45..]
: path;
lblStatus.Text = $"Scanning: {files:N0} files, {folders:N0} folders scanned... {display}";
// Update the root node text with running totals if we have data (skip during sub-scan)
if (_subScanNode == null && _scanRoot != null && treeResults.Nodes.Count > 0)
{
RefreshTree();
}
}
private void RefreshTree()
{
var root = _scanRoot;
if (root == null || treeResults.Nodes.Count == 0) return;
treeResults.BeginUpdate();
var rootNode = treeResults.Nodes[0];
UpdateNodeFromInfo(rootNode, root, root.TotalSize);
treeResults.EndUpdate();
}
private void UpdateNodeFromInfo(TreeNode node, FolderInfo folder, long rootTotal)
{
node.Text = folder.Name;
node.Tag = folder;
// Build a map of existing child nodes by path
var existingChildren = new Dictionary<string, TreeNode>();
foreach (TreeNode child in node.Nodes)
{
if (child.Tag is FolderInfo fi)
existingChildren[fi.Path] = child;
}
// Get children sorted by size descending
List<FolderInfo> sortedChildren;
lock (folder.Children)
{
sortedChildren = folder.Children.OrderByDescending(c => c.TotalSize).ToList();
}
// Sync tree nodes with folder children
// Remove nodes for children that no longer exist
for (int i = node.Nodes.Count - 1; i >= 0; i--)
{
if (node.Nodes[i].Tag is FolderInfo fi && !sortedChildren.Any(c => c.Path == fi.Path))
node.Nodes.RemoveAt(i);
}
// Add/update nodes in sorted order
for (int i = 0; i < sortedChildren.Count; i++)
{
var childInfo = sortedChildren[i];
TreeNode childNode;
if (existingChildren.TryGetValue(childInfo.Path, out var existing))
{
childNode = existing;
// Move to correct position if needed
if (node.Nodes.IndexOf(childNode) != i)
{
node.Nodes.Remove(childNode);
node.Nodes.Insert(i, childNode);
}
}
else
{
childNode = new TreeNode(childInfo.Name);
node.Nodes.Insert(i, childNode);
}
UpdateNodeFromInfo(childNode, childInfo, rootTotal);
}
}
private void OnScanComplete()
{
StopTimers();
var wasCancelled = _cts?.IsCancellationRequested ?? false;
var root = _scanRoot;
ResetUiAfterScan();
if (root == null)
{
lblStatus.Text = wasCancelled ? "Scan cancelled (no data)." : "Scan returned no results.";
progressBar.Value = 0;
return;
}
// Final tree refresh
treeResults.BeginUpdate();
treeResults.Nodes.Clear();
var rootNode = BuildTreeNode(root, root.TotalSize);
treeResults.Nodes.Add(rootNode);
treeResults.EndUpdate();
btnExport.Enabled = true;
progressBar.Value = wasCancelled ? 0 : 100;
var skipped = _skippedCount > 0 ? $" | {_skippedCount} junctions skipped" : "";
var cancelNote = wasCancelled ? " [PARTIAL — cancelled]" : "";
lblStatus.Text = $"Done — {FormatSize(root.TotalSize)} total | " +
$"{root.FileCount:N0} files | {root.FolderCount:N0} folders " +
$"(depth: {_maxDepth}){skipped}{cancelNote}";
}
private void ResetUiAfterScan()
{
_scanRunning = false;
btnScan.Text = "Scan";
btnScan.IsPrimary = true;
btnScan.Enabled = true;
btnBrowse.Enabled = true;
nudDepth.Enabled = true;
progressBar.IsMarquee = false;
}
// ── Fast Win32 scanner ──────────────────────────────────────────
private struct FastEntry
{
public string Name;
public bool IsDirectory;
public bool IsReparsePoint;
public long Size;
}
private static List<FastEntry> FastScanDirectory(string path)
{
var results = new List<FastEntry>();
var searchPath = path.Length > 0 && path[^1] == '\\'
? path + "*"
: path + "\\*";
var handle = FindFirstFileW(searchPath, out var findData);
if (handle == INVALID_HANDLE_VALUE)
return results;
try
{
do
{
var name = findData.cFileName;
if (name == "." || name == "..")
continue;
var isDir = (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
var isReparse = (findData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
long size = isDir ? 0 : ((long)findData.nFileSizeHigh << 32) | findData.nFileSizeLow;
results.Add(new FastEntry
{
Name = name,
IsDirectory = isDir,
IsReparsePoint = isReparse,
Size = size
});
} while (FindNextFileW(handle, out findData));
}
finally
{
FindClose(handle);
}
return results;
}
// ── Scan engine ─────────────────────────────────────────────────
private FolderInfo ScanFolder(string path, int currentDepth, CancellationToken ct)
{
var info = new FolderInfo { Path = path, Name = Path.GetFileName(path) };
if (string.IsNullOrEmpty(info.Name))
info.Name = path;
// Store root reference early for partial results (skip during sub-scan)
if (currentDepth == 0 && _subScanNode == null)
_scanRoot = info;
ct.ThrowIfCancellationRequested();
Volatile.Write(ref _currentPath, path);
// Single Win32 call gets all entries with attributes + sizes
List<FastEntry> entries;
try
{
entries = FastScanDirectory(path);
}
catch
{
info.AccessDenied = true;
return info;
}
// Process files from this directory
foreach (var entry in entries)
{
if (entry.IsDirectory) continue;
info.OwnSize += entry.Size;
info.FileCount++;
Interlocked.Increment(ref _filesScanned);
}
// Collect subdirectories
var subdirs = new List<(string FullPath, string Name)>();
foreach (var entry in entries)
{
if (!entry.IsDirectory) continue;
if (entry.IsReparsePoint)
{
Interlocked.Increment(ref _skippedCount);
continue;
}
subdirs.Add((Path.Combine(path, entry.Name), entry.Name));
}
// Decide parallel vs sequential
if (currentDepth <= ParallelDepthLimit && subdirs.Count > 1)
{
ScanSubdirsParallel(info, subdirs, currentDepth, ct);
}
else
{
ScanSubdirsSequential(info, subdirs, currentDepth, ct);
}
info.TotalSize += info.OwnSize;
Interlocked.Increment(ref _foldersScanned);
return info;
}
private void ScanSubdirsParallel(FolderInfo parent, List<(string FullPath, string Name)> subdirs,
int currentDepth, CancellationToken ct)
{
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = Environment.ProcessorCount,
CancellationToken = ct
};
Parallel.ForEach(subdirs, parallelOptions, subdir =>
{
ct.ThrowIfCancellationRequested();
try
{
if (currentDepth < _maxDepth)
{
var child = ScanFolder(subdir.FullPath, currentDepth + 1, ct);
lock (parent.Children)
{
parent.Children.Add(child);
}
Interlocked.Add(ref parent._totalSize, child.TotalSize);
Interlocked.Add(ref parent._fileCount, child.FileCount);
Interlocked.Add(ref parent._folderCount, child.FolderCount + 1);
}
else
{
var (size, files, folders) = TallyFolder(subdir.FullPath, 0, ct);
Interlocked.Add(ref parent._totalSize, size);
Interlocked.Add(ref parent._fileCount, files);
Interlocked.Add(ref parent._folderCount, folders + 1);
}
}
catch (OperationCanceledException) { throw; }
catch { }
});
}
private void ScanSubdirsSequential(FolderInfo parent, List<(string FullPath, string Name)> subdirs,
int currentDepth, CancellationToken ct)
{
foreach (var subdir in subdirs)
{
ct.ThrowIfCancellationRequested();
try
{
if (currentDepth < _maxDepth)
{
var child = ScanFolder(subdir.FullPath, currentDepth + 1, ct);
parent.Children.Add(child);
parent.TotalSize += child.TotalSize;
parent.FileCount += child.FileCount;
parent.FolderCount += child.FolderCount + 1;
}
else
{
var (size, files, folders) = TallyFolder(subdir.FullPath, 0, ct);
parent.TotalSize += size;
parent.FileCount += files;
parent.FolderCount += folders + 1;
}
}
catch (OperationCanceledException) { throw; }
catch { }
}
}
private (long size, int files, int folders) TallyFolder(string path, int depth, CancellationToken ct)
{
if (depth > HardRecursionLimit)
return (0, 0, 0);
ct.ThrowIfCancellationRequested();
Volatile.Write(ref _currentPath, path);
List<FastEntry> entries;
try
{
entries = FastScanDirectory(path);
}
catch
{
return (0, 0, 0);
}
long size = 0;
int files = 0;
int folders = 0;
foreach (var entry in entries)
{
if (!entry.IsDirectory)
{
size += entry.Size;
files++;
Interlocked.Increment(ref _filesScanned);
}
}
foreach (var entry in entries)
{
if (!entry.IsDirectory) continue;
if (entry.IsReparsePoint)
{
Interlocked.Increment(ref _skippedCount);
continue;
}
ct.ThrowIfCancellationRequested();
try
{
var fullPath = Path.Combine(path, entry.Name);
var (s, f, d) = TallyFolder(fullPath, depth + 1, ct);
size += s;
files += f;
folders += d + 1;
}
catch (OperationCanceledException) { throw; }
catch { }
}
Interlocked.Increment(ref _foldersScanned);
return (size, files, folders);
}
// ── Tree building (final) ───────────────────────────────────────
private static TreeNode BuildTreeNode(FolderInfo folder, long rootTotal)
{
var node = new TreeNode(folder.Name) { Tag = folder };
List<FolderInfo> sorted;
lock (folder.Children)
{
sorted = folder.Children.OrderByDescending(c => c.TotalSize).ToList();
}
foreach (var child in sorted)
{
node.Nodes.Add(BuildTreeNode(child, rootTotal));
}
return node;
}
// ── UI events ───────────────────────────────────────────────────
private void TreeResults_NodeMouseDoubleClick(object? sender, TreeNodeMouseClickEventArgs e)
{
if (e.Node?.Tag is FolderInfo info)
{
try
{
Process.Start(new ProcessStartInfo
{
FileName = info.Path,
UseShellExecute = true
});
}
catch { }
}
}
private void BtnExport_Click(object sender, EventArgs e)
{
if (treeResults.Nodes.Count == 0) return;
using var dlg = new SaveFileDialog
{
Filter = "Text Files|*.txt|CSV Files|*.csv",
FileName = "FolderSizes"
};
if (dlg.ShowDialog() != DialogResult.OK) return;
var root = (FolderInfo)treeResults.Nodes[0].Tag!;
using var writer = new StreamWriter(dlg.FileName);
if (dlg.FilterIndex == 2)
{
writer.WriteLine("Path,Size (Bytes),Size,Files,Folders");
ExportCsv(writer, root);
}
else
{
ExportText(writer, root, 0);
}
lblStatus.Text = $"Exported to {dlg.FileName}";
}
private static void ExportText(StreamWriter writer, FolderInfo folder, int indent)
{
var prefix = new string(' ', indent * 2);
writer.WriteLine($"{prefix}{folder.Name} -- {FormatSize(folder.TotalSize)} ({folder.FileCount:N0} files)");
List<FolderInfo> sorted;
lock (folder.Children)
{
sorted = folder.Children.OrderByDescending(c => c.TotalSize).ToList();
}
foreach (var child in sorted)
ExportText(writer, child, indent + 1);
}
private static void ExportCsv(StreamWriter writer, FolderInfo folder)
{
writer.WriteLine($"\"{folder.Path}\",{folder.TotalSize},\"{FormatSize(folder.TotalSize)}\",{folder.FileCount},{folder.FolderCount}");
List<FolderInfo> sorted;
lock (folder.Children)
{
sorted = folder.Children.OrderByDescending(c => c.TotalSize).ToList();
}
foreach (var child in sorted)
ExportCsv(writer, child);
}
private static string FormatSize(long bytes)
{
string[] units = ["B", "KB", "MB", "GB", "TB"];
double size = bytes;
int unit = 0;
while (size >= 1024 && unit < units.Length - 1)
{
size /= 1024;
unit++;
}
return unit == 0 ? $"{size:N0} {units[unit]}" : $"{size:N2} {units[unit]}";
}
// ── Sub-scan (right-click "Scan from here") ──────────────────────
private void CtxTree_Opening(object? sender, CancelEventArgs e)
{
if (_scanRunning)
{
e.Cancel = true;
return;
}
var pos = treeResults.PointToClient(Cursor.Position);
var node = treeResults.GetNodeAt(pos);
if (node?.Tag is not FolderInfo)
{
e.Cancel = true;
return;
}
treeResults.SelectedNode = node;
}
private void CtxScanFromHere_Click(object? sender, EventArgs e)
{
var node = treeResults.SelectedNode;
if (node?.Tag is not FolderInfo folderInfo || _scanRunning) return;
var path = folderInfo.Path;
if (!Directory.Exists(path))
{
MessageBox.Show($"Folder no longer exists:\n{path}", "Invalid Path",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
_subScanNode = node;
_maxDepth = (int)nudDepth.Value;
// Set up UI — keep existing tree visible
progressBar.Value = 0;
progressBar.IsMarquee = true;
lblStatus.Text = $"Scanning {folderInfo.Name}...";
btnScan.Text = "Cancel";
btnScan.IsPrimary = false;
btnBrowse.Enabled = false;
btnExport.Enabled = false;
nudDepth.Enabled = false;
_skippedCount = 0;
_filesScanned = 0;
_foldersScanned = 0;
_currentPath = "";
_cts = new CancellationTokenSource();
_scanRunning = true;
// Start timers
_uiTimer = new System.Windows.Forms.Timer { Interval = 200 };
_uiTimer.Tick += UiTimer_Tick;
_uiTimer.Start();
_animTimer = new System.Windows.Forms.Timer { Interval = 16 };
_animTimer.Tick += (_, _) => progressBar.AdvanceAnimation();
_animTimer.Start();
var ct = _cts.Token;
Task.Run(() =>
{
FolderInfo? result = null;
try
{
result = ScanFolder(path, 0, ct);
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
BeginInvoke(() =>
{
StopTimers();
_subScanNode = null;
ResetUiAfterScan();
lblStatus.Text = "Sub-scan failed.";
MessageBox.Show($"{ex.GetType().Name}: {ex.Message}",
"Scan Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
});
return;
}
BeginInvoke(() => OnSubScanComplete(node, result));
}, ct);
}
private void OnSubScanComplete(TreeNode node, FolderInfo? newInfo)
{
StopTimers();
var wasCancelled = _cts?.IsCancellationRequested ?? false;
if (newInfo == null)
{
_subScanNode = null;
ResetUiAfterScan();
lblStatus.Text = wasCancelled ? "Sub-scan cancelled." : "Sub-scan returned no results.";
progressBar.Value = 0;
return;
}
MergeSubScan(node, newInfo);
_subScanNode = null;
ResetUiAfterScan();
btnExport.Enabled = true;
progressBar.Value = wasCancelled ? 0 : 100;
var root = treeResults.Nodes.Count > 0 ? treeResults.Nodes[0].Tag as FolderInfo : null;
if (root != null)
{
var skipped = _skippedCount > 0 ? $" | {_skippedCount} junctions skipped" : "";
var cancelNote = wasCancelled ? " [PARTIAL]" : "";
lblStatus.Text = $"Done — {FormatSize(root.TotalSize)} total | " +
$"{root.FileCount:N0} files | {root.FolderCount:N0} folders{skipped}{cancelNote}";
}
}
private void MergeSubScan(TreeNode node, FolderInfo newInfo)
{
var oldInfo = node.Tag as FolderInfo;
long sizeDelta = newInfo.TotalSize - (oldInfo?.TotalSize ?? 0);
int fileDelta = newInfo.FileCount - (oldInfo?.FileCount ?? 0);
int folderDelta = newInfo.FolderCount - (oldInfo?.FolderCount ?? 0);
// Replace in parent FolderInfo's Children list
if (node.Parent?.Tag is FolderInfo parentInfo && oldInfo != null)
{
lock (parentInfo.Children)
{
var idx = parentInfo.Children.IndexOf(oldInfo);
if (idx >= 0)
parentInfo.Children[idx] = newInfo;
}
}
else if (node.Parent == null)
{
// Re-scanning root node
_scanRoot = newInfo;
}
// Propagate size deltas up the ancestor chain
var ancestor = node.Parent;
while (ancestor?.Tag is FolderInfo ancestorInfo)
{
Interlocked.Add(ref ancestorInfo._totalSize, sizeDelta);
Interlocked.Add(ref ancestorInfo._fileCount, fileDelta);
Interlocked.Add(ref ancestorInfo._folderCount, folderDelta);
ancestor = ancestor.Parent;
}
// Update this node and rebuild its subtree
node.Tag = newInfo;
node.Text = newInfo.Name;
long rootTotal = GetTreeRootTotal();
treeResults.BeginUpdate();
node.Nodes.Clear();
List<FolderInfo> sorted;
lock (newInfo.Children)
{
sorted = newInfo.Children.OrderByDescending(c => c.TotalSize).ToList();
}
foreach (var child in sorted)
{
node.Nodes.Add(BuildTreeNode(child, rootTotal));
}
node.Expand();
treeResults.EndUpdate();
treeResults.Invalidate();
}
private long GetTreeRootTotal()
{
if (treeResults.Nodes.Count > 0 && treeResults.Nodes[0].Tag is FolderInfo rootInfo)
return rootInfo.TotalSize;
return _scanRoot?.TotalSize ?? 0;
}
private void StopTimers()
{
_uiTimer?.Stop();
_uiTimer?.Dispose();
_uiTimer = null;
_animTimer?.Stop();
_animTimer?.Dispose();
_animTimer = null;
}
// ── Card panel paint (rounded border) ───────────────────────────
private void PaintCardPanel(object? sender, PaintEventArgs e)
{
if (sender is not Panel panel) return;
var g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
var rect = new RectangleF(0.5f, 0.5f, panel.Width - 1f, panel.Height - 1f);
using var path = ModernTheme.RoundedRect(rect, ModernTheme.CardRadius);
using var pen = new Pen(ModernTheme.CardBorder, 1f);
g.DrawPath(pen, path);
}
// ── Textbox wrapper paint (rounded border, accent on focus) ─────
private void PnlPathWrapper_Paint(object? sender, PaintEventArgs e)
{
if (sender is not Panel panel) return;
var g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
var rect = new RectangleF(0.5f, 0.5f, panel.Width - 1f, panel.Height - 1f);
using var path = ModernTheme.RoundedRect(rect, ModernTheme.ButtonRadius);
var borderColor = txtPath.Focused ? ModernTheme.Accent : ModernTheme.CardBorder;
var thickness = txtPath.Focused ? 2f : 1f;
using var pen = new Pen(borderColor, thickness);
g.DrawPath(pen, path);
}
private void TxtPath_FocusChanged(object? sender, EventArgs e)
{
pnlPathWrapper.Invalidate();
}
private void Form1_KeyDown(object? sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
BtnScan_Click(this, EventArgs.Empty);
}
}
}
public class FolderInfo
{
public string Path { get; set; } = "";
public string Name { get; set; } = "";
public long OwnSize { get; set; }
public bool AccessDenied { get; set; }
public List<FolderInfo> Children { get; set; } = [];
// Backing fields for Interlocked access in parallel scans
internal long _totalSize;
internal long _fileCount;
internal long _folderCount;
public long TotalSize
{
get => Interlocked.Read(ref _totalSize);
set => Interlocked.Exchange(ref _totalSize, value);
}
public int FileCount
{
get => (int)Interlocked.Read(ref _fileCount);
set => Interlocked.Exchange(ref _fileCount, value);
}
public int FolderCount
{
get => (int)Interlocked.Read(ref _folderCount);
set => Interlocked.Exchange(ref _folderCount, value);
}
}