Repository navigation
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
991 lines (914 loc) · 44.6 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
991 lines (914 loc) · 44.6 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
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.Win32;
using TempFileCleaner.Controls;
namespace TempFileCleaner
{
/// <summary>
/// App for testing code snipets
/// </summary>
public partial class MainWindow : Window
{
bool _frameCapture = false;
DispatcherTimer _captureTimer = null;
#region [Properties]
int _totalFail = 0;
int _totalSuccess = 0;
int _totalExclude = 0;
long _totalBytes = 0;
double sfcCount = 0;
double _pbUpperMaximum = 15000; // user could have many files, or only a few, so estimate a ceiling to start
double _cfgWinHeight = 750;
double _cfgWinWidth = 1100;
int _cfgMonthAge = -12;
bool _cfgReportOnly = false;
bool _cfgFirstRun = true;
bool _UAC = false;
string[] _cfgExcludeFolders = null;
CancellationTokenSourceEnhanced _cts;
TaskMan taskMan = new TaskMan();
public static readonly DependencyProperty IsMainLoadedProperty = DependencyProperty.Register(
nameof(IsMainLoaded),
typeof(bool),
typeof(MainWindow),
new PropertyMetadata(false));
public bool IsMainLoaded
{
get => (bool)GetValue(IsMainLoadedProperty);
set => SetValue(IsMainLoadedProperty, value);
}
public event EventHandler<List<FileResult>> CleanupCompleted;
public event EventHandler<Exception> CleanupError;
// Add any folder names you want to ignore here.
readonly string[] IgnoredFolders =
{
"WinSAT", // Windows System Assessment Tool (benchmarks system hardware—CPU, memory, disk, and graphics—to calculate the Windows Experience Index score)
"WER", // Windows Error Reporting
"Diagnostics", // Windows Diagnostics logs
"AppCrash", // Common Application crash dumps
"$PatchCache$", // Windows Installer cache
"SoftwareDistribution" // Windows Update temp
};
// Add any folder names (with wildcards) you want to ignore here.
readonly string[] IgnoredWildcardFolders =
{
"WinSAT",
"WER",
"Diagnostics",
"Diag*",
"AppCrash",
"$PatchCache$",
"SoftwareDistribution",
"*Cache*"
};
#endregion
public MainWindow()
{
InitializeComponent();
#region [Event Hooks]
this.Loaded += OnMainWindowLoaded;
this.Closing += OnMainWindowClosing;
//this.KeyUp += OnMainWindowKeyUp;
CleanupError += OnCleanupError;
//ObservableCollectionExample.CollectionChanged += FileLog_CollectionChanged;
ConfigManager.OnError += (s, e) =>
{
Dispatcher.Invoke(() =>
{
WpfMessageBox.Show($"ConfigManager error:{Environment.NewLine}{e.Message}", false, true, owner: this);
});
};
MethodTimer.LogHandler = (msg) =>
{
Debug.WriteLine($"[TIMER] {msg}");
ConfigManager.Set("ExecutionTime", msg);
};
#endregion
}
#region [Events]
/// <summary>
/// For <see cref="ObservableCollection{T}"/> event if MVVM pattern is adopted.
/// </summary>
/// <param name="sender"><see cref="ObservableCollection{T}"/></param>
/// <param name="e"><see cref="System.Collections.Specialized.NotifyCollectionChangedAction"/></param>
void FileLog_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
lstFiles.ScrollIntoView(e.NewItems[e.NewItems.Count - 1]);
}
}
void OnMainWindowLoaded(object sender, RoutedEventArgs e)
{
if (_frameCapture)
RemovePreviousCaptures();
this.Title = $"{App.GetCurrentAssemblyName()} v{App.GetCurrentAssemblyVersion()}";
spProgress.Visibility = Visibility.Hidden;
btnCancel.Visibility = Visibility.Hidden;
cbReport.IsChecked = _cfgReportOnly = ConfigManager.Get("ReportOnly", defaultValue: true);
_cfgMonthAge = ConfigManager.Get("MonthAge", defaultValue: -12);
tbMonths.Text = $"{_cfgMonthAge}";
// Read folder array
_cfgExcludeFolders = ConfigManager.Get<string[]>("ExcludeFolders");
// Or use alternative method
//_cfgExcludeFolders = ConfigManager.GetArray("ExcludeFolders");
//var savedCodes = ConfigManager.Get<List<int>>("WarningCodes") ?? new List<int>();
this.Width = _cfgWinWidth = ConfigManager.Get("WindowWidth", defaultValue: 1100.0);
this.Height = _cfgWinHeight = ConfigManager.Get("WindowHeight", defaultValue: 750.0);
if (string.IsNullOrWhiteSpace(ConfigManager.Get("WindowLeft")) ||
string.IsNullOrWhiteSpace(ConfigManager.Get("WindowTop")))
{
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
}
else
{
this.WindowStartupLocation = WindowStartupLocation.Manual;
this.Top = ConfigManager.Get("WindowTop", defaultValue: 200.0);
this.Left = ConfigManager.Get("WindowLeft", defaultValue: 300.0);
}
_cfgFirstRun = ConfigManager.Get("FirstRun", defaultValue: true);
if (_cfgFirstRun)
{
WpfMessageBox.Show($"Welcome to {App.GetCurrentAssemblyName()} v{App.GetCurrentAssemblyVersion()} !{Environment.NewLine}" +
$"This app will identify and delete old temp files from your system.{Environment.NewLine}" +
$"You can configure the age threshold and choose to run in report-only mode if you want to review files before deletion.{Environment.NewLine}" +
$"Use the cancel button to stop the process at any time.{Environment.NewLine}" +
$"Items marked with an orange dot will NOT be removed,{Environment.NewLine}items marked with a green dot WILL be removed."
, false, false, fontSize: 13.0, owner: this);
}
_ = taskMan?.Run(async () =>
{
await Task.Delay(220);
Dispatcher.Invoke(() => { IsMainLoaded = true; });
});
/*
if (Debugger.IsAttached)
{
StartupAnalyzer.RunTest();
//Test.Run(dryRun: true);
//var next8a =Extensions.NextHighestMultipleOf8(8);
//var next8b =Extensions.NextHighestMultipleOf8(9);
//var next16a =Extensions.NextHighestMultipleOf16(16);
//var next16b =Extensions.NextHighestMultipleOf16(17);
//scFilesCleaned.Value = "5000"; // testing DoubleAnimation on StatCard
}
*/
}
void OnMainWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
ConfigManager.Set("WindowWidth", this.Width >= 400 ? this.Width : 500);
ConfigManager.Set("WindowHeight", this.Height >= 200 ? this.Height : 300);
ConfigManager.Set("WindowLeft", this.Left >= 0 ? this.Left : 300);
ConfigManager.Set("WindowTop", this.Top >= 0 ? this.Top : 200);
ConfigManager.Set("ReportOnly", (bool)cbReport.IsChecked);
ConfigManager.Set("FirstRun", false);
if (!int.TryParse(tbMonths.Text, out int months)) { months = -12; }
ConfigManager.Set("MonthAge", months);
if (_cfgExcludeFolders != null)
ConfigManager.Set("ExcludeFolders", _cfgExcludeFolders);
else
ConfigManager.Set("ExcludeFolders", IgnoredFolders); // default
// Testing array save/load
//List<int> codes = new List<int> { 101, 202, 303, 404, 505 };
//ConfigManager.Set("WarningCodes", codes);
}
void btnCancelClick(object sender, RoutedEventArgs e)
{
_cts?.Cancel();
}
void OnCleanupError(object sender, Exception e)
{
Dispatcher.Invoke(() =>
{
var result = WpfMessageBox.Show($"Cleanup error:{Environment.NewLine}{e.Message}", true, true, owner: this);
// Check for cancel click
if (result.HasValue && !result.Value)
_cts?.Cancel();
});
}
async void btnCleanupClick(object sender, RoutedEventArgs e)
{
double totalCount = 0;
// Reset counters
_totalBytes = 0;
_totalFail = 0;
_totalSuccess = 0;
_totalExclude = 0;
scBytesTotal.Dispatcher.Invoke(new Action(() => { scBytesTotal.Value = _totalBytes.ToFileSize(); }));
scFilesCleaned.Dispatcher.Invoke(new Action(() => { scFilesCleaned.Value = _totalSuccess.ToString(); }));
scFilesFailed.Dispatcher.Invoke(new Action(() => { scFilesFailed.Value = _totalFail.ToString(); }));
scFilesExcluded.Dispatcher.Invoke(new Action(() => { scFilesExcluded.Value = _totalExclude.ToString(); }));
_cts = new CancellationTokenSourceEnhanced(TimeSpan.FromMinutes(5)); // reset our token
lstFiles.Items.Clear();
btnStart.Visibility = Visibility.Hidden;
cbReport.IsEnabled = tbMonths.IsEnabled = false;
spProgress.Visibility = btnCancel.Visibility = pbCleaning.Visibility = Visibility.Visible;
pbCleaning.Minimum = 0;
pbCleaning.Maximum = _pbUpperMaximum;
if (!int.TryParse(tbMonths.Text, out int months)) { _cfgMonthAge = -6; }
_cfgReportOnly = (bool)cbReport.IsChecked;
// Deleted Files
var progressSuccess = new Progress<FileResult>(fr =>
{
lstFiles.Items.Add(fr);
totalCount++;
_totalSuccess++;
if (totalCount > pbCleaning.Maximum)
pbCleaning.Maximum = totalCount + (_pbUpperMaximum / 8.0);
pbCleaning.Value = totalCount;
scFilesCleaned.Dispatcher.BeginInvoke(new Action(() =>
{
scFilesCleaned.Value = _totalSuccess.ToString();
scBytesTotal.Value = _totalBytes.ToFileSize();
}));
});
// Couldn't Remove
var progressFailed = new Progress<FileResult>(fr =>
{
lstFiles.Items.Add(fr);
totalCount++;
_totalFail++;
if (totalCount > pbCleaning.Maximum)
pbCleaning.Maximum = totalCount + (_pbUpperMaximum / 8.0);
pbCleaning.Value = totalCount;
scFilesFailed.Dispatcher.BeginInvoke(new Action(() =>
{
scFilesFailed.Value = _totalFail.ToString();
}));
});
// Excluded Files
var progressExclude = new Progress<FileResult>(fr =>
{
lstFiles.Items.Add(fr);
totalCount++;
_totalExclude++;
if (totalCount > pbCleaning.Maximum)
pbCleaning.Maximum = totalCount + (_pbUpperMaximum / 8.0);
pbCleaning.Value = totalCount;
scFilesExcluded.Dispatcher.BeginInvoke(new Action(() =>
{
scFilesExcluded.Value = _totalExclude.ToString();
scBytesTotal.Value = _totalBytes.ToFileSize();
}));
});
// Delegate for SFC command
var progressSfc = new Progress<FileResult>(fr =>
{
Dispatcher.Invoke(() => { lstFiles.Items.Add(fr); });
if (sfcCount == 0)
sfcCount = pbCleaning.Value;
sfcCount++;
if (sfcCount > pbCleaning.Maximum)
pbCleaning.Maximum = sfcCount + (_pbUpperMaximum / 8.0);
pbCleaning.Value = sfcCount;
});
try
{
//List<FileResult> allFailed = await CleanOldTempFilesAsync(_cfgMonthAge, _cfgReportOnly, _cts.Token, progressFailed, progressSuccess, progressExclude);
var allTimed = MethodTimer.TimeAsync(() => CleanOldTempFilesAsync(_cfgMonthAge, _cfgReportOnly, _cts.Token, progressFailed, progressSuccess, progressExclude), "CleanOldTempFilesAsync");
var tsk = await allTimed;
}
catch (OperationCanceledException)
{
WpfMessageBox.Show("Cleanup was cancelled by the user.", false, true, owner: this);
}
catch (Exception ex)
{
WpfMessageBox.Show($"Cleanup: {ex.Message}", false, true, owner: this);
}
finally
{
await Dispatcher.BeginInvoke(new Action(() =>
{
scBytesTotal.Value = $"{_totalBytes.ToFileSize()}";
pbCleaning.Value = pbCleaning.Maximum;
if (lstFiles.Items.Count > 0)
{
var lastItem = lstFiles.Items[lstFiles.Items.Count - 1];
lstFiles.ScrollIntoView(lastItem);
}
}));
if (_cfgReportOnly)
{
WpfMessageBox.Show($"Total files that could be cleaned: {_totalSuccess}{Environment.NewLine}" +
$"Total files skipped due to error: {_totalFail}{Environment.NewLine}" +
$"Total files excluded: {_totalExclude}{Environment.NewLine}" +
$"Total file size: {_totalBytes.ToFileSize()}",
false, false, owner: this);
if (_UAC)
{
var dskscn = WpfMessageBox.Show($"Would you like to run the local system's file checker?{Environment.NewLine}{Environment.NewLine}Time remaining on your current token: {_cts.TimeRemaining.ToReadableTime()}", true, false, owner: this);
if (dskscn.HasValue && dskscn.Value)
{
var result = await MethodTimerAsync.TimeAsync(async () => await RunSystemFileChecker(_cts.Token, progressSfc));
WpfMessageBox.Show($"SFC process finished.{Environment.NewLine}SFC attempt took {result.ToReadableTime()}.", false, false, owner: this);
}
}
}
else
{
WpfMessageBox.Show($"Total files cleaned: {_totalSuccess}{Environment.NewLine}" +
$"Total files skipped: {_totalFail}{Environment.NewLine}" +
$"Total files excluded: {_totalExclude}{Environment.NewLine}" +
$"Total file size: {_totalBytes.ToFileSize()}",
false, false, owner: this);
if (_UAC)
{
var dskcln = WpfMessageBox.Show($"Would you like to run the local system's DiskClean tool?", true, false, owner: this);
if (dskcln.HasValue && dskcln.Value)
{
PreConfigureDiskCleanup();
RunDiskCleanup(_cts.Token);
RunSystemFileChecker(_cts.Token, progressSfc);
}
}
}
_cts?.Dispose();
pbCleaning.Value = 0;
cbReport.IsEnabled = tbMonths.IsEnabled = true;
btnStart.Visibility = Visibility.Visible;
btnCancel.Visibility = Visibility.Hidden;
pbCleaning.Visibility = spProgress.Visibility = Visibility.Hidden;
}
}
void OnSelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
// Get the ListBox that triggered the event
var lb = sender as ListBox;
// Ensure an item was actually selected (not just deselected)
if (lb?.SelectedItem != null)
{
// Cast the selected item to its type (e.g. file path)
var selectedFile = lb.SelectedItem as FileResult;
// You could also trigger your cleanup logic or open a preview here
Debug.WriteLine($"[INFO] User selected: {selectedFile?.FilePath}");
}
}
#endregion
#region [Work Methods]
/// <summary>
/// Identifies and deletes temp files older than <paramref name="months"/>.
/// Returns a list of files that could not be deleted (in use, access denied, etc).
/// </summary>
public async Task<List<FileResult>> CleanOldTempFilesAsync(int months, bool reportOnly, CancellationToken ct, IProgress<FileResult> progressFail = null, IProgress<FileResult> progressSuccess = null, IProgress<FileResult> progressExclude = null)
{
if (months >= 0)
months *= -1;
return await taskMan.Run(async () =>
{
var failedFiles = new List<FileResult>();
DateTime cutoffDate = DateTime.Now.AddMonths(months);
string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var browserCache1 = Path.GetTempPath().Replace(@"\Temp", @"\Google\Chrome\User Data\Default\Cache");
var browserCache2 = Path.GetTempPath().Replace(@"\Temp", @"\Microsoft\Edge\User Data\Default\Cache");
var browserCache3 = Path.GetTempPath().Replace(@"\Temp", @"\Microsoft\Edge\User Data\Default\Code Cache");
var browserCache4 = Path.GetTempPath().Replace(@"\Temp", @"\Microsoft\Edge\User Data\Default\GPUCache");
// Firefox does a good job of cleaning itself, so we'll ignore it.
var crashDumps = Path.GetTempPath().Replace(@"\Temp", @"\CrashDumps");
string[] tempFolders =
{
@"C:\Windows\Temp",
@"C:\Windows\SoftwareDistribution\Download",
//@"C:\Windows\System32\LogFiles",
Path.GetTempPath(),
Path.Combine(userProfile, "Downloads"),
Environment.GetEnvironmentVariable("TMP"),
Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.User),
Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.Machine),
appData, browserCache1, browserCache2, browserCache3, browserCache4, crashDumps
};
// List of folder fragments to ignore
var excludeFolders = new List<string>
{
"\\Prefetch\\",
"\\Program Files\\",
"\\Program Files (x86)\\",
"\\AppData\\Roaming\\",
"\\inetpub\\",
"\\Servicing\\LCU\\",
"\\WinSAT\\", // System Assessment Tool (%systemroot%\performance\winsat\datastore)
"\\WinSxS\\", // Windows Updates
"\\System32\\" };
// De-dupe the folder list
var filtered = tempFolders.Select(p => p.ToLower().TrimEnd('\\')).Distinct().ToList();
foreach (string folder in filtered)
{
if (!Directory.Exists(folder) || ct.IsCancellationRequested)
continue;
try
{
Logger.WriteInfo($"Scanning folder \"{folder}\"");
foreach (string filePath in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))
{
if (ct.IsCancellationRequested)
break;
// Does the file path contain any excluded folder names?
bool isExcluded = excludeFolders.Any(exf => filePath.ToLower().Contains(exf.ToLower()));
if (isExcluded)
{
//Debug.WriteLine($"[INFO] Skipping excluded file/folder \"{filePath}\"");
progressExclude?.Report(new FileResult { FilePath = filePath, IsSuccess = false });
try
{
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.LastWriteTime < cutoffDate)
{
// Include excluded files in the total size reported.
_totalBytes += fileInfo.Length;
}
}
catch { }
continue;
}
try
{
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.LastWriteTime < cutoffDate)
{
_totalBytes += fileInfo.Length;
if (reportOnly)
{
progressSuccess?.Report(new FileResult { FilePath = filePath, IsSuccess = true });
}
else
{
// Some downloaded archives/files could be set as read-only by default.
if (fileInfo.IsReadOnly)
fileInfo.IsReadOnly = false;
fileInfo.Delete();
progressSuccess?.Report(new FileResult { FilePath = filePath, IsSuccess = true });
}
//await Task.Delay(1); // Delays process, but smooths out the ProgBar jumpiness
}
}
catch
{
failedFiles.Add(new FileResult { FilePath = filePath, IsSuccess = false });
progressFail?.Report(new FileResult { FilePath = filePath, IsSuccess = false });
//await Task.Delay(1); // Delays process, but smooths out the ProgBar jumpiness
}
}
}
catch (Exception ex)
{
Logger.WriteWarn($"Error processing folder \"{folder}\": {ex.Message}");
CleanupError?.Invoke(this, ex);
}
await Task.Delay(10);
}
CleanupCompleted?.Invoke(this, failedFiles);
return failedFiles;
}, ct);
}
/// <summary>
/// Identifies and deletes temp files older than <paramref name="months"/>.
/// Returns a list of files that could not be deleted (in use, access denied, etc).
/// </summary>
public async Task<List<string>> CleanOldTempFilesAsyncPrevious(int months, bool reportOnly, CancellationToken ct, IProgress<string> progressFail = null, IProgress<string> progressSuccess = null)
{
if (months >= 0)
months *= -1;
return await taskMan.Run(async () =>
{
List<string> failedFiles = new List<string>();
DateTime cutoffDate = DateTime.Now.AddMonths(months);
string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string[] tempFolders =
{
Path.GetTempPath(),
Path.Combine(userProfile, "Downloads"),
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
Environment.GetEnvironmentVariable("TMP"),
Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.User),
Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.Machine),
@"C:\Windows\Temp"
};
var filtered = tempFolders.Select(p => p.ToLower().TrimEnd('\\')).Distinct().ToList();
foreach (string folder in filtered)
{
if (!Directory.Exists(folder) || ct.IsCancellationRequested)
continue;
try
{
foreach (string filePath in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))
{
if (ct.IsCancellationRequested)
break;
if (ShouldIgnore(filePath))
{
Debug.WriteLine($"[WARNING] Ignoring \"{filePath}\"");
continue;
}
try
{
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.LastWriteTime < cutoffDate)
{
if (reportOnly)
{
progressSuccess?.Report(filePath);
}
else
{
if (fileInfo.IsReadOnly)
fileInfo.IsReadOnly = false;
fileInfo.Delete();
progressSuccess?.Report(filePath);
}
// Smooth out the ProgBar jumpiness
//await Task.Delay(1);
}
}
catch
{
failedFiles.Add(filePath);
progressFail?.Report(filePath);
// Smooth out the ProgBar jumpiness
//await Task.Delay(1);
}
}
}
catch (Exception ex)
{
Logger.WriteWarn($"Error processing folder \"{folder}\": {ex.Message}");
CleanupError?.Invoke(this, ex);
}
}
await Task.Delay(1);
//CleanupCompleted?.Invoke(this, failedFiles);
return failedFiles;
}, ct);
}
#endregion
#region [Helpers]
async Task RunSystemFileChecker(CancellationToken ct, IProgress<FileResult> progress = null)
{
await taskMan.Run(async () =>
{
try
{
var startInfo = new ProcessStartInfo
{
FileName = "sfc.exe",
Arguments = "/scannow",
//WorkingDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32"),
UseShellExecute = false, // MUST be true for elevation
Verb = "runas", // Triggers UAC elevation
CreateNoWindow = false, // SFC must run in a console window
RedirectStandardOutput = true, // Capture normal output
RedirectStandardError = true, // Capture error output
StandardOutputEncoding = System.Text.Encoding.Unicode // SFC often uses UTF-16
};
using (var process = new Process { StartInfo = startInfo })
{
// Subscribe to events for real-time updates
process.OutputDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
progress?.Report(new FileResult { FilePath = $"[SFC] {e.Data}", IsSuccess = true });
//Application.Current.Dispatcher.Invoke(() => lstFiles.Items.Add(e.Data));
}
};
process.ErrorDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
progress?.Report(new FileResult { FilePath = $"[SFC] {e.Data}", IsSuccess = false });
//Application.Current.Dispatcher.Invoke(() => lstFiles.Items.Add("ERROR: " + e.Data));
}
};
process.Start();
// Start the asynchronous read
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// NOTE: process.WaitForExitAsync(ct) isn't available in older .NET Framework versions
#region [Legacy Framework Process Cancel]
// Create a task that completes when the process exits
var processExitTask = taskMan.Run(() => process.WaitForExit());
// Create a task that completes when the token is cancelled
var cancellationTask = Task.Delay(-1, ct);
// Wait for whichever happens first
var completedTask = await Task.WhenAny(processExitTask, cancellationTask);
// If cancellation was requested then kill the external process
if (completedTask == cancellationTask)
{
if (!process.HasExited)
process.Kill();
ct.ThrowIfCancellationRequested();
}
#endregion
await Task.Delay(250);
}
}
catch (OperationCanceledException)
{
Dispatcher.Invoke(() =>
{
WpfMessageBox.Show("User canceled the SFC process!", false, false, owner: this);
});
}
catch (System.ComponentModel.Win32Exception) // User clicked "No" on the UAC prompt
{
Dispatcher.Invoke(() =>
{
WpfMessageBox.Show("Administrative access is required to fix system files.", false, true, owner: this);
});
}
catch (Exception ex)
{
Dispatcher.Invoke(() =>
{
WpfMessageBox.Show($"RunSystemFileChecker{Environment.NewLine}{ex.Message}", false, true, owner: this);
});
}
});
}
/// <summary><code>
/// "cleanmgr /sagerun:1"
/// Runs the Windows Disk Cleanup tool using a pre-configured profile (ID 1)
/// created by the cleanmgr /sageset:1 command. It automates file deletion,
/// including temp files, system logs, and cache, based on selected settings
/// without requiring further user input.
/// "cleanmgr /lowdisk"
/// Opens the utility with all checkboxes selected by default, which is useful
/// for a "complete scan" when the volume is running with limited free space.
/// </code></summary>
async Task RunDiskCleanup(CancellationToken ct, bool sageRun = true)
{
await taskMan.Run(async () =>
{
try
{
var startInfo = new ProcessStartInfo
{
FileName = "cleanmgr.exe",
Arguments = sageRun ? "/sagerun:1" : "/lowdisk /d C",
Verb = "runas",
UseShellExecute = true
};
using (var process = new Process { StartInfo = startInfo })
{
// NOTE: process.WaitForExitAsync(ct) isn't available in older .NET Framework versions
#region [Legacy framework process cancel]
// Create a task that completes when the process exits
var processExitTask = taskMan.Run(() => process.WaitForExit());
// Create a task that completes when the token is cancelled
var cancellationTask = Task.Delay(-1, ct);
// Wait for whichever happens first
var completedTask = await Task.WhenAny(processExitTask, cancellationTask);
// If cancellation was requested then kill the external process
if (completedTask == cancellationTask)
{
if (!process.HasExited)
process.Kill();
ct.ThrowIfCancellationRequested();
}
#endregion
}
}
catch (OperationCanceledException)
{
Dispatcher.Invoke(() =>
{
WpfMessageBox.Show("User canceled the SFC process!", false, false, owner: this);
});
}
catch (System.ComponentModel.Win32Exception) // User clicked "No" on the UAC prompt
{
Dispatcher.Invoke(() =>
{
WpfMessageBox.Show("Administrative access is required to clean system files.", false, true, owner: this);
});
}
catch (Exception ex)
{
Dispatcher.Invoke(() =>
{
WpfMessageBox.Show($"RunDiskCleanAuto{Environment.NewLine}{ex.Message}", false, true, owner: this);
});
}
});
}
/// <summary>
/// Adds <c>StateFlags0001</c> to registry for cleanmgr.
/// </summary>
void PreConfigureDiskCleanup()
{
const string registryPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches";
try
{
// Open the HKLM base key with write access (Requires Admin)
using (RegistryKey rootKey = Registry.LocalMachine.OpenSubKey(registryPath, true))
{
if (rootKey != null)
{
// Iterate through every cleanup category (Recycle Bin, Temporary Files, Update Cleanup, etc.)
foreach (string subKeyName in rootKey.GetSubKeyNames())
{
using (RegistryKey subKey = rootKey.OpenSubKey(subKeyName, true))
{
// Set StateFlags0001 to 2 (Checked)
// Note: "0001" corresponds to the "1" in /sageset:1
subKey?.SetValue("StateFlags0001", 2, RegistryValueKind.DWord);
}
}
WpfMessageBox.Show("Registry pre-configured for Set 1.", false, false, owner: this);
}
}
}
catch (UnauthorizedAccessException)
{
WpfMessageBox.Show($"Administrator privileges are required to modify registry settings.{Environment.NewLine}You can run \"cleanmgr /sageset:1\" from an elevated command prompt, then check all the boxes.", false, true, owner: this);
}
catch (Exception ex)
{
WpfMessageBox.Show($"{ex.Message}{Environment.NewLine}Try running \"cleanmgr /sageset:1\" from an elevated command prompt, then check all the boxes.", false, true, owner: this);
}
}
bool ShouldIgnore(string path)
{
try
{
if (_cfgExcludeFolders == null)
return false;
// Normalize separators and split into segments
var segments = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
foreach (var segment in segments)
{
foreach (var ignored in _cfgExcludeFolders)
{
if (segment.Equals(ignored, StringComparison.OrdinalIgnoreCase))
return true;
}
}
}
catch
{
// If something goes wrong, fail safe and do NOT ignore
}
return false;
}
bool ShouldIgnoreWithWildcards(string path)
{
try
{
if (_cfgExcludeFolders == null)
return false;
var segments = path.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
foreach (var segment in segments)
{
foreach (var pattern in _cfgExcludeFolders)
{
if (WildcardMatch(segment, pattern))
return true;
}
}
}
catch
{
// Fail-safe: do NOT ignore if something goes wrong
}
return false;
}
bool WildcardMatch(string text, string pattern)
{
// Escape regex special chars except * and ?
string regex = "^" + Regex.Escape(pattern)
.Replace("\\*", ".*")
.Replace("\\?", ".") + "$";
return Regex.IsMatch(text, regex, RegexOptions.IgnoreCase
);
}
#endregion
#region [StatCard Click Handler]
//void scFilesCleaned_Click(object sender, RoutedEventArgs e)
//{
// Debug.WriteLine($"Card clicked");
//}
void StatCard_Click(object sender, StatCardClickEventArgs e)
{
if (e == null || string.IsNullOrWhiteSpace(e.Title))
return;
switch (e.Title)
{
case "Files Cleaned":
Debug.WriteLine($"[INFO] Clicked: {e.Title} = {e.Value}");
break;
case "Total Bytes":
Debug.WriteLine($"[INFO] Clicked: {e.Title} = {e.Value}");
break;
case "Files Excluded":
Debug.WriteLine($"[INFO] Clicked: {e.Title} = {e.Value}");
break;
case "Files Failed":
Debug.WriteLine($"[INFO] Clicked: {e.Title} = {e.Value}");
break;
}
}
#endregion
#region [Frame Capture]
void OnMainWindowKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
if (_frameCapture)
{
_captureTimer?.Stop();
_frameCapture = false;
int count = 0;
foreach (var enc in _encoder)
{
count++;
var filePath = $"capture_{count:D3}.png";
try
{
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
enc.Save(fs);
}
}
catch (Exception) { }
}
_encoder.Clear();
if (_captureTimer != null)
_captureTimer.Tick -= captureTimer_Tick;
}
else
{
RemovePreviousCaptures();
_frameCapture = true;
if (_captureTimer == null)
{
_captureTimer = new System.Windows.Threading.DispatcherTimer();
// Adjust this time based on the desired framerate for the GIF.
_captureTimer.Interval = TimeSpan.FromMilliseconds(100);
_captureTimer.Tick += captureTimer_Tick;
_captureTimer.Start();
}
_captureTimer?.Start();
}
}
else if (e.Key != Key.PrintScreen)
{
_captureTimer?.Stop();
this.Close();
}
}
List<PngBitmapEncoder> _encoder = new List<PngBitmapEncoder>();
void captureTimer_Tick(object? sender, EventArgs e)
{
SaveElementAsPng(hostGrid);
}
void SaveElementAsPng(FrameworkElement element)
{
if (element == null) { return; }
Size size = new Size(element.ActualWidth, element.ActualHeight);
element.Measure(size);
//element.Arrange(new Rect(size));
var rtb = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);
rtb.Render(element);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
_encoder.Add(encoder);
}
/// <summary>
/// Remove old capture images, if they exist.
/// </summary>
void RemovePreviousCaptures()
{
var pngFiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "capture*.png", SearchOption.TopDirectoryOnly);
foreach (var fn in pngFiles)
{
try { File.Delete(fn); }
catch { }
}
}
#endregion
}
#region [Models]
public class FileResult
{
public string FilePath { get; set; }
public bool IsSuccess { get; set; }
public string StatusIcon => IsSuccess ? "Check" : "Alert";
public string StatusColor => IsSuccess ? "#00FF21" : "#FFAE00";
public string StatusText => IsSuccess ? "#F2F2F2" : "#C9C9C9";
}
#endregion
}