-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
2890 lines (2600 loc) · 125 KB
/
Form1.cs
File metadata and controls
2890 lines (2600 loc) · 125 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
using Microsoft.Win32.TaskScheduler;
using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Threading;
using System.Windows.Forms;
using Action = System.Action;
using File = System.IO.File;
using ThreadState = System.Threading.ThreadState;
using Timer = System.Timers.Timer;
namespace SimpleBackup
{
public partial class Form1 : Form
{
private static Thread backupThread = null;
private static Thread appUpdateThread = null;
private static Timer transferStatTimer = null;
private static bool backupIsRunning = false;
private static bool autoRun = false;
private static SmtpClient smtpClient = null;
private static bool isSendingEmail = false;
private static bool isSendingTestEmail = false;
private static bool isCheckingForUpdateOnLaunch = false;
private static readonly int maxMD5ExtraTransferAttempts = 1;
private static readonly int maxThreadAbortWaitTime = 1000;
private static readonly int maxInfoTextBoxLines = 400;
private static readonly string updateServerUrl = "https://github.com/Aelstraz/SimpleBackup/releases/latest";
private static readonly int updateServerRequestTimeOut = 5000;
//variables for tracking transfer stats
private static DateTime backupStartTime = new DateTime();
private static string currentFilePathStat = null;
private static ulong totalFileSizeStat = 0;
private static ulong totalTransferedFileSizeStat = 0;
private static ulong lastFileSizeStat = 0;
private static ulong currentTransferedFileSizeStat = 0;
private static List<ulong> transferSpeedHistoryListStat = new List<ulong>();
private static readonly int transferSpeedHistoryMaxSize = 25;
/// <summary>
/// Creates a new form, checks passed runtime args and checks for any new app updates from: <see href="https://github.com/Aelstraz/SimpleBackup/releases/latest"></see>
/// </summary>
/// <param name="args">Passed runtime arguments, supported args include: "scheduledRun" (begins the application in auto-run mode, used with Windows Task Scheduler)</param>
public Form1(string[] args)
{
InitializeComponent();
Settings.Load();
Log.OnLogUpdated += OnLogUpdatedCallback;
//get build version
string buildVersion = "v" + System.Diagnostics.FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
Log.WriteLine("--Welcome to SimpleBackup " + buildVersion + "--");
//set window title with the latest build version
Text = "SimpleBackup " + buildVersion;
//check if args were passed for automated run
if (args.Length > 0 && args.Contains("scheduledRun"))
{
autoRun = true;
WindowState = FormWindowState.Minimized;
StartBackupThread();
}
//only check for update on launch if set, and auto close is not set
if (Settings.data.checkForUpdateOnLaunch && (!autoRun || autoRun && !Settings.data.scheduleAutoClose))
{
isCheckingForUpdateOnLaunch = true;
//check for latest app version
StartAppUpdateCheckThread();
}
}
/// <summary>
/// Begins the backup process and starts a background thread to continue the backup process (in order to not block the main/UI thread)
/// </summary>
private void StartBackupThread()
{
//check if a backup is already running
if (!backupIsRunning)
{
//set UI elements to starting values
infoTextBox.Text = "";
Log.WriteLine("--Starting backup--");
backupIsRunning = true;
backupButton.Text = "Stop Backup";
backupProgressBar.Value = 0;
//save the backup start time
backupStartTime = DateTime.Now;
//create a new thread to run the backup on
ThreadStart threadStart = new ThreadStart(Backup);
backupThread = new Thread(threadStart);
backupThread.IsBackground = true;
backupThread.Start();
//start a timer to track transfer stats
transferStatTimer = new Timer(1000);
transferStatTimer.Elapsed += TransferStatTimerElapsed;
transferStatTimer.Start();
}
else
{
//cancel backup early if user clicks yes
DialogResult dialogResult = MessageBox.Show("Backup in progress. Are you sure you wish to cancel?", "Caution", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dialogResult == DialogResult.Yes)
{
StopBackupEarly();
}
}
}
/// <summary>
/// Runs through the main process of collecting directory data, comparing directory data, transfering/deleting files and updating backup folders
/// </summary>
private void Backup()
{
if (!BackupPathsAreValid())
{
FinishTransfer();
return;
}
List<TransferDirectory> transferDirectoryList = new List<TransferDirectory>();
List<TransferFile> transferFileList = new List<TransferFile>();
List<Tuple<string, string>> backupFolderUpdateList = new List<Tuple<string, string>>();
int totalNumberOfFiles = 0;
ulong totalSizeOfFiles = 0;
CollectAndCompareDirectoryData(ref transferDirectoryList, ref transferFileList, ref totalNumberOfFiles, ref totalSizeOfFiles, ref backupFolderUpdateList);
//delete any files/folders from the root dst that aren't found in the root src
DeleteRootUnlinkedFiles(ref backupFolderUpdateList);
//check if we found any files to be transfered
if (totalNumberOfFiles == 0)
{
Log.WriteLine("No new/modified files found");
}
else
{
Log.WriteLine("Number of files to transfer: " + totalNumberOfFiles);
Log.WriteLine("Total data size: " + ConvertFileSize(totalSizeOfFiles));
Log.WriteLine("Starting file transfer");
//calback to main thread
if (backupThread.ThreadState != ThreadState.AbortRequested && backupThread.ThreadState != ThreadState.Aborted)
{
Invoke(new Action(() => OnStartBackupCallback(totalSizeOfFiles)));
}
StartTransfer(ref transferDirectoryList, ref transferFileList);
}
//update any modified backup folders with the latest DateTime
UpdateBackupFolderNames(ref backupFolderUpdateList);
//calback to main thread
if (backupThread.ThreadState != ThreadState.AbortRequested && backupThread.ThreadState != ThreadState.Aborted)
{
Invoke(new Action(() => FinishTransfer()));
}
}
/// <summary>
/// Collects all directory/file data from the source and destination paths, and their sub-directories at every depth, and compares them to see what needs to be transfered
/// </summary>
/// <param name="transferDirectoryList">Stores which directories (and their contents) need to be transfered</param>
/// <param name="transferFileList">Stores which individual files need to be transfered</param>
/// <param name="totalNumberOfFiles">Adds the total number of files which need to be transfered</param>
/// <param name="totalSizeOfFiles">Adds the total size of files which need to be transfered</param>
/// <param name="backupFolderUpdateList">Stores which backup folders need to be updated after transfer</param>
private void CollectAndCompareDirectoryData(ref List<TransferDirectory> transferDirectoryList, ref List<TransferFile> transferFileList, ref int totalNumberOfFiles, ref ulong totalSizeOfFiles, ref List<Tuple<string, string>> backupFolderUpdateList)
{
int numberOfFoundFilesInDst = 0;
ulong totalSizeOfFilesFoundInDst = 0;
TransferDirectory transferDirectory = new TransferDirectory();
BackupDirectory srcBackupDirectory = new BackupDirectory();
BackupDirectory dstBackupDirectory;
BackupComparison backupComparison;
string srcPath;
string dstPath;
string dstFullPath;
bool isFolder;
TransferFile transferFile = new TransferFile();
FileInfo srcFileInfo = null;
FileInfo dstFileInfo;
BackupFile backupFile;
string dstFileName;
bool writeFile;
string backupName;
Tuple<string, string> backupFolderPathToUpdate;
Log.WriteLine("Collecting file/directory data");
//collect file/directory data at each src
for (int i = 0; i < Settings.data.sourcePaths.Count; i++)
{
srcPath = Settings.data.sourcePaths[i];
isFolder = PathIsFolder(srcPath);
//check if src is folder or file
if (isFolder)
{
if (Directory.Exists(srcPath))
{
//collect src directory data
srcBackupDirectory = new BackupDirectory(srcPath, new List<BackupDirectory>(), new List<BackupFile>());
GetDirectoryDataRecursive(ref srcBackupDirectory, applyFilter: true);
//add src directory data to transfer directory list
transferDirectory = new TransferDirectory(srcBackupDirectory,
new string[Settings.data.destinationPaths.Count],
new BackupComparison[Settings.data.destinationPaths.Count],
new string[Settings.data.destinationPaths.Count]);
transferDirectoryList.Add(transferDirectory);
}
else
{
Log.WriteLine("Folder to backup could not be found " + srcPath, isError: true);
continue;
}
}
else
{
if (File.Exists(srcPath))
{
//collect single file data
srcFileInfo = new FileInfo(srcPath);
backupFile = new BackupFile(srcPath, (ulong)srcFileInfo.Length, srcFileInfo.LastWriteTime);
//add single file data to transfer file list
transferFile = new TransferFile(backupFile, new string[Settings.data.destinationPaths.Count], new string[Settings.data.destinationPaths.Count]);
transferFileList.Add(transferFile);
}
else
{
Log.WriteLine("File to backup could not be found " + srcPath, isError: true);
continue;
}
}
//collect file/directory data at each dst and compare it against the current src data
for (int x = 0; x < Settings.data.destinationPaths.Count; x++)
{
dstPath = Settings.data.destinationPaths[x];
//get the oldest backup name at dst path
backupName = GetOldestBackupFolderName(dstPath);
if (backupName != null)
{
backupFolderPathToUpdate = new Tuple<string, string>(dstPath, backupName);
//check that we haven't already added the backup name
if (!backupFolderUpdateList.Contains(backupFolderPathToUpdate))
{
//add backup names that need to be updated once we've finished transfering files
backupFolderUpdateList.Add(backupFolderPathToUpdate);
}
}
else
{
//couldn't find oldest backup, create new backup name
backupName = GetNewBackupFolderName();
}
//check if src is folder or file
if (isFolder)
{
//src is folder
//collect dst directory data
dstFullPath = Path.Combine(dstPath, backupName, Path.GetFileName(srcBackupDirectory.path));
dstBackupDirectory = new BackupDirectory(dstFullPath, new List<BackupDirectory>(), new List<BackupFile>());
GetDirectoryDataRecursive(ref dstBackupDirectory);
//compare the dst directory with src directory (to see what needs to be transfered)
backupComparison = new BackupComparison(new List<BackupComparison>(), new bool[srcBackupDirectory.backupFileList.Count]);
numberOfFoundFilesInDst = 0;
CompareDirectoryDataRecursive(ref srcBackupDirectory, ref dstBackupDirectory, ref backupComparison, ref numberOfFoundFilesInDst, ref totalSizeOfFilesFoundInDst, dstFullPath);
//check if we found any files to transfer after comparing the src and dst directory
if (numberOfFoundFilesInDst > 0)
{
//add the dst path, backup name and backup comparison data to the current transfer directory
transferDirectory.dstPathArray[x] = dstPath;
transferDirectory.backupComparisonArray[x] = backupComparison;
transferDirectory.backupNameArray[x] = backupName;
//add to total
totalSizeOfFiles += totalSizeOfFilesFoundInDst;
totalNumberOfFiles += numberOfFoundFilesInDst;
}
}
else
{
//src is file
//collect dst single file data
dstFileName = Path.Combine(dstPath, backupName, srcFileInfo.Name);
writeFile = false;
if (!Settings.data.transferUnchangedFiles && File.Exists(dstFileName))
{
//dst file already exists
dstFileInfo = new FileInfo(dstFileName);
backupFile = new BackupFile(dstFileName, (ulong)dstFileInfo.Length, dstFileInfo.LastWriteTime);
//check if the src file data matches dst file data
if (transferFile.backupFile.Equals(backupFile))
{
if (Settings.data.useMD5ForComparison && !MD5HashesAreEqual(srcFileInfo.FullName, dstFileInfo.FullName))
{
//the dst file is different from the src, add the file to be transfered/overwritten
writeFile = true;
}
}
else
{
//the dst file is different from the src, add the file to be transfered/overwritten
writeFile = true;
}
}
else
{
//file doesn't exist at the dst, add the file to be transfered
writeFile = true;
}
if (writeFile)
{
//add the dst path and backup name to the current transfer file
transferFile.dstPathArray[x] = dstPath;
transferFile.backupNameArray[x] = backupName;
//add to total
totalNumberOfFiles++;
totalSizeOfFiles += transferFile.backupFile.fileSize;
}
}
}
}
}
/// <summary>
/// Collects all file/folder data at the specified directory path, and if checkChildren is set to true, then it will also collect all file/folder data from each sub-directory at every depth, recursively
/// </summary>
/// <param name="backupDirectory">Stores all files/folders found in the directory</param>
/// <param name="directoryPath">The path of the directory to collect data from</param>
/// <param name="checkChildren">Specifies whether or not to also collect data from each sub-directory recursively</param>
/// <param name="applyFilter">Specifies whether or not to apply the user-defined file/path filters when collecting data</param>
private void GetDirectoryDataRecursive(ref BackupDirectory backupDirectory, bool checkChildren = true, bool applyFilter = false)
{
//check if directory exists, and if it passes the filter
if (!Directory.Exists(backupDirectory.path) || (applyFilter && !PathPassesBackupFilters(backupDirectory.path)))
{
backupDirectory.path = null;
return;
}
FileInfo fileInfo;
//backupDirectory.path = directoryPath;
//add each file to the backup directory
foreach (string filePath in Directory.GetFiles(backupDirectory.path))
{
try
{
//check if the file passes the filter
if (!applyFilter || (applyFilter && PathPassesBackupFilters(filePath)))
{
fileInfo = new FileInfo(filePath);
backupDirectory.backupFileList.Add(new BackupFile(fileInfo.Name, (ulong)fileInfo.Length, fileInfo.LastWriteTime));
}
}
catch (ThreadAbortException)
{
break;
}
catch (Exception e)
{
Log.WriteLine("Couldn't get data from file: '" + filePath + "'. " + e.Message, isError: true);
}
}
//add each sub-directory to the backup directory
foreach (string subDirectoryPath in Directory.GetDirectories(backupDirectory.path))
{
try
{
BackupDirectory subDirectory = new BackupDirectory(subDirectoryPath, new List<BackupDirectory>(), new List<BackupFile>());
//run recursively
if (checkChildren)
{
GetDirectoryDataRecursive(ref subDirectory, checkChildren, applyFilter);
}
//check if the sub-directory path passes the filter
else if (!checkChildren && applyFilter && !PathPassesBackupFilters(subDirectoryPath))
{
subDirectory.path = null;
}
//only add sub-directory if its path is valid
if (!string.IsNullOrEmpty(subDirectory.path))
{
backupDirectory.subDirectoryList.Add(subDirectory);
}
}
catch (ThreadAbortException)
{
break;
}
catch (Exception e)
{
Log.WriteLine("Couldn't get data from sub-directory: '" + subDirectoryPath + "'. " + e.Message, isError: true);
}
}
}
/// <summary>
/// Recursivley compares all file data (to check which files need to be transfered) between the source and destination directories, and each of their sub-directories at every depth
/// </summary>
/// <param name="srcBackupDirectory">The source backup directory containing all the folders/files that it currently holds</param>
/// <param name="dstBackupDirectory">The destination backup directory containing all the folders/files that it currently holds, if null is supplied then the whole source directory is written to the destination</param>
/// <param name="backupComparison">Stores which files are to be ignored when transfering</param>
/// <param name="totalNumberOfFiles">Adds the total number of files which need to be transfered</param>
/// <param name="totalSizeOfFiles">Adds the total size of files which need to be transfered</param>
/// <param name="dstFullPath">The full path of the dst directory being compared</param>
private void CompareDirectoryDataRecursive(ref BackupDirectory srcBackupDirectory, ref BackupDirectory dstBackupDirectory, ref BackupComparison backupComparison, ref int totalNumberOfFiles, ref ulong totalSizeOfFiles, string dstFullPath)
{
int foundFileIndex;
string srcPath;
string dstPath;
bool writeFile = false;
bool writeAll = false;
//if the dst folder is null or empty, then the whole dst folder needs to be written
if (string.IsNullOrEmpty(dstBackupDirectory.path))
{
writeAll = true;
//create directory at dst path
try
{
Directory.CreateDirectory(dstFullPath);
}
catch (ThreadAbortException)
{
return;
}
catch (Exception e)
{
Log.WriteLine("Couldn't create directory at dst: '" + dstFullPath + "'. " + e.Message, isError: true);
return;
}
}
//compare files
for (int i = 0; i < srcBackupDirectory.backupFileList.Count; i++)
{
//if writeAll isn't set, do file comparisons
if (!writeAll)
{
writeFile = false;
foundFileIndex = -1;
//compare src files against dst files
for (int x = 0; x < dstBackupDirectory.backupFileList.Count; x++)
{
//check if src file exists at the dst
if (srcBackupDirectory.backupFileList[i].name == dstBackupDirectory.backupFileList[x].name)
{
//the file exists at both locations
foundFileIndex = x;
break;
}
}
//check that we found a matching file, and that if we're going to transfer it regardless
if (foundFileIndex != -1 && !Settings.data.transferUnchangedFiles)
{
//check if the file hasn't been modified
if (srcBackupDirectory.backupFileList[i].Equals(dstBackupDirectory.backupFileList[foundFileIndex]))
{
srcPath = Path.Combine(srcBackupDirectory.path, srcBackupDirectory.backupFileList[i].name);
dstPath = Path.Combine(dstBackupDirectory.path, dstBackupDirectory.backupFileList[foundFileIndex].name);
//check if we're using md5 checks and if so, if the md5 hashes are equal
if (Settings.data.useMD5ForComparison && !MD5HashesAreEqual(srcPath, dstPath))
{
//md5 hashes do no match or we're not checking md5, file needs to be transfered
writeFile = true;
}
}
else
{
//files do not match, file needs to be transfered
writeFile = true;
}
}
else
{
//we didn't find a file, or we're going to transfer it regardless, file needs to be tranfered
writeFile = true;
}
}
//check if file needs to be written
if (writeAll || writeFile)
{
//add to total
totalNumberOfFiles++;
totalSizeOfFiles += (ulong)srcBackupDirectory.backupFileList[i].fileSize;
}
else
{
//ignore the file for backup since it doesn't need to backed up
backupComparison.filesToIgnoreArray[i] = true;
}
}
//delete any files/folders from the dst backup that aren't in found in src
if (!string.IsNullOrEmpty(dstBackupDirectory.path) && !string.IsNullOrEmpty(dstBackupDirectory.path))
{
DeleteUnlinkedFiles(ref srcBackupDirectory, ref dstBackupDirectory);
}
BackupDirectory srcSubDirectoryRef;
BackupDirectory dstSubDirectoryRef;
BackupComparison backupComparisonRef;
string srcSubDirectoryName;
//compare subdirectories recursively
for (int i = 0; i < srcBackupDirectory.subDirectoryList.Count; i++)
{
//add new backup comparison data for each subdirectory
backupComparison.subDirectoryList.Add(new BackupComparison(new List<BackupComparison>(), new bool[srcBackupDirectory.subDirectoryList[i].backupFileList.Count]));
//setup references to pass recursively
backupComparisonRef = backupComparison.subDirectoryList.Last();
dstSubDirectoryRef = new BackupDirectory(null, new List<BackupDirectory>(), new List<BackupFile>());
srcSubDirectoryRef = srcBackupDirectory.subDirectoryList[i];
srcSubDirectoryName = Path.GetFileName(srcBackupDirectory.subDirectoryList[i].path);
if (!string.IsNullOrEmpty(dstBackupDirectory.path))
{
//check if src folder exists at the dst
for (int x = 0; x < dstBackupDirectory.subDirectoryList.Count; x++)
{
if (srcSubDirectoryName == Path.GetFileName(dstBackupDirectory.subDirectoryList[x].path))
{
//folder exists, set it as our reference to be compared recursively
dstSubDirectoryRef = dstBackupDirectory.subDirectoryList[x];
break;
}
}
}
CompareDirectoryDataRecursive(ref srcSubDirectoryRef, ref dstSubDirectoryRef, ref backupComparisonRef, ref totalNumberOfFiles, ref totalSizeOfFiles, Path.Combine(dstFullPath, srcSubDirectoryName));
}
}
/// <summary>
/// Begins transfering files from each source directory to each destination directory
/// </summary>
/// <param name="transferDirectoryList">The list of directories and their contents that need to be transfered</param>
/// <param name="transferFileList">The list of individual files that need to be transfered</param>
private void StartTransfer(ref List<TransferDirectory> transferDirectoryList, ref List<TransferFile> transferFileList)
{
int filesBackedUpCount = 0;
string dstBackupFolder;
string dstPath;
string dstRootPath;
BackupDirectory srcDirectoryRef;
//transfer each directory
for (int i = 0; i < transferDirectoryList.Count; i++)
{
//transfer to each dst
for (int x = 0; x < transferDirectoryList[i].dstPathArray.Length; x++)
{
dstBackupFolder = "";
try
{
dstPath = transferDirectoryList[i].dstPathArray[x];
if (!string.IsNullOrEmpty(dstPath))
{
dstBackupFolder = Path.Combine(dstPath, transferDirectoryList[i].backupNameArray[x]);
dstRootPath = Path.Combine(dstBackupFolder, Path.GetFileName(transferDirectoryList[i].srcDirectory.path));
//create/overwrite backup folder directory
Directory.CreateDirectory(dstBackupFolder);
//recursively transfer all files to the current dst
srcDirectoryRef = transferDirectoryList[i].srcDirectory;
TransferDirectoryFilesRecursive(ref srcDirectoryRef, ref transferDirectoryList[i].backupComparisonArray[x], dstRootPath, ref filesBackedUpCount);
}
}
catch (ThreadAbortException)
{
break;
}
catch (Exception e)
{
Log.WriteLine("Couldn't create/overwrite dst directory: '" + dstBackupFolder + "' when starting transfer of folder: '" + transferDirectoryList[i].srcDirectory.path + "'. " + e.Message, isError: true);
}
}
}
//transfer single files
for (int i = 0; i < transferFileList.Count; i++)
{
for (int x = 0; x < transferFileList[i].dstPathArray.Length; x++)
{
dstBackupFolder = "";
try
{
dstPath = transferFileList[i].dstPathArray[x];
if (!string.IsNullOrEmpty(dstPath))
{
dstBackupFolder = Path.Combine(dstPath, transferFileList[i].backupNameArray[x]);
dstRootPath = Path.Combine(dstBackupFolder, Path.GetFileName(transferFileList[i].backupFile.name));
//create/overwrite directory
Directory.CreateDirectory(dstBackupFolder);
//transfer the file to dst
TransferFile(transferFileList[i].backupFile.name, dstRootPath, transferFileList[i].backupFile.lastModified, transferFileList[i].backupFile.fileSize);
filesBackedUpCount++;
}
}
catch (ThreadAbortException)
{
break;
}
catch (Exception e)
{
Log.WriteLine("Couldn't create/overwrite dst directory: '" + dstBackupFolder + "' when starting transfer of file: '" + transferFileList[i].backupFile.name + "'. " + e.Message, isError: true);
}
}
}
}
/// <summary>
/// Recursively transfers all files in the current backup directory, and for each sub-directory at every depth
/// </summary>
/// <param name="backupDirectory">The backup directory containing all the folders/files that it currently holds</param>
/// <param name="backupComparison">The backup comparison containing which files need to ignored when transfering</param>
/// <param name="dstPath">The backup destination path</param>
/// <param name="filesBackedUpCount">Adds the total number of files that have been transfered</param>
private void TransferDirectoryFilesRecursive(ref BackupDirectory backupDirectory, ref BackupComparison backupComparison, string dstPath, ref int filesBackedUpCount)
{
if (!Directory.Exists(dstPath))
{
Log.WriteLine("Couldn't find dst directory for transfer: '" + dstPath + "'", isError: true);
return;
}
string srcPath = "";
for (int i = 0; i < backupDirectory.backupFileList.Count; i++)
{
try
{
//check that the file isn't being ignored
if (!backupComparison.filesToIgnoreArray[i])
{
srcPath = Path.Combine(backupDirectory.path, backupDirectory.backupFileList[i].name);
//transfer the file to dst
TransferFile(srcPath, Path.Combine(dstPath, backupDirectory.backupFileList[i].name), backupDirectory.backupFileList[i].lastModified, backupDirectory.backupFileList[i].fileSize);
filesBackedUpCount++;
}
}
catch (ThreadAbortException)
{
break;
}
catch (Exception e)
{
Log.WriteLine("Couldn't transfer file: '" + srcPath + "'. " + e.Message, isError: true);
}
}
BackupDirectory subDirectoryRef;
BackupComparison subDirectoryComparisonRef;
//recursively transfer all files in each sub-directory
for (int i = 0; i < backupDirectory.subDirectoryList.Count; i++)
{
//collect references
subDirectoryRef = backupDirectory.subDirectoryList[i];
subDirectoryComparisonRef = backupComparison.subDirectoryList[i];
TransferDirectoryFilesRecursive(ref subDirectoryRef, ref subDirectoryComparisonRef, Path.Combine(dstPath, Path.GetFileName(backupDirectory.subDirectoryList[i].path)), ref filesBackedUpCount);
}
}
/// <summary>
/// Transfers an individual file from the source path to the destination path. If MD5 transfer is enabled by the user,
/// then the two files will also compare their MD5 checksums, and if the comparison fails, another transfer attempt is made
/// </summary>
/// <param name="srcPath">The path of the file to transfer</param>
/// <param name="dstPath">The destination path (where to transfer the file)</param>
/// <param name="fileLastModified">The DateTime the file was last modified</param>
/// <param name="fileSize">The size of the file to transfer</param>
/// <param name="extraMD5TransferAttempts">Used internally to track how many additional transfer attempts have been made when using the MD5 checksum, should be set to 0 by default</param>
private void TransferFile(string srcPath, string dstPath, DateTime fileLastModified, ulong fileSize, int extraMD5TransferAttempts = 0)
{
if (!File.Exists(srcPath))
{
Log.WriteLine("Couldn't find file at src to transfer: '" + srcPath + "'", isError: true);
if (backupThread.ThreadState != ThreadState.AbortRequested && backupThread.ThreadState != ThreadState.Aborted)
{
Invoke(new Action(() => OnFailedFileTransferCallback(fileSize)));
}
return;
}
//callback to main thread
if (backupThread.ThreadState != ThreadState.AbortRequested && backupThread.ThreadState != ThreadState.Aborted)
{
Invoke(new Action(() => OnStartFileTransferCallback(dstPath)));
}
bool finishTransfer = false;
FileStream srcStream = null;
FileStream dstStream = null;
Log.WriteLine("Transfering file: " + Path.GetFileName(srcPath) + " (" + ConvertFileSize(fileSize) + ")");
try
{
ulong freeBytesForUser;
ulong totalBytes;
ulong freeBytes;
string diskDriveLetter = Path.GetPathRoot(dstPath).Replace("\\", "");
//get free disk space at dst
if (GetDiskFreeSpaceEx(diskDriveLetter, out freeBytesForUser, out totalBytes, out freeBytes))
{
//check if the dst drive has enough space for the file
if (fileSize <= freeBytesForUser)
{
//transfer file from src to dst
srcStream = File.OpenRead(srcPath);
dstStream = File.Create(dstPath);
srcStream.CopyTo(dstStream);
dstStream.Flush();
srcStream.Close();
srcStream = null;
dstStream.Close();
dstStream = null;
//update file write time
File.SetLastWriteTime(dstPath, fileLastModified);
//do MD5 checks if required
if (Settings.data.useMD5ForTransfer)
{
if (!MD5HashesAreEqual(srcPath, dstPath))
{
//attempt to re-transfer the file if MD5 hashes dont match
if (extraMD5TransferAttempts <= maxMD5ExtraTransferAttempts)
{
Log.WriteLine("MD5 file hashes do not match, attempting to transfer file again");
TransferFile(srcPath, dstPath, fileLastModified, fileSize, extraMD5TransferAttempts++);
}
//max number of re-transfer attempts reached and still failed to transfer the file
else
{
Log.WriteLine("MD5 file hashes do not match, even after additional attempts. Deleting corrupted file: " + dstPath, isError: true);
//delete the corrupted file
File.Delete(dstPath);
finishTransfer = true;
}
}
else
{
finishTransfer = true;
}
}
else
{
finishTransfer = true;
}
}
else
{
Log.WriteLine("Disk " + diskDriveLetter + " does not have enough space. Couldn't write file: " + srcPath + " to " + diskDriveLetter + ". " +
"File size: " + ConvertFileSize(fileSize) + " vs disk space left: " + ConvertFileSize(freeBytesForUser), isError: true);
}
}
else
{
Log.WriteLine("Could not get free disk space from disk " + diskDriveLetter, isError: true);
}
}
catch (ThreadAbortException)
{
//close streams if thread aborted
if (srcStream != null)
{
srcStream.Close();
}
if (dstStream != null)
{
dstStream.Close();
}
return;
}
catch (Exception e)
{
Log.WriteLine("Couldn't transfer file: '" + dstPath + "'. " + e.Message, isError: true);
}
//callback to main thread
if (finishTransfer && backupThread.ThreadState != ThreadState.AbortRequested && backupThread.ThreadState != ThreadState.Aborted)
{
Invoke(new Action(() => OnFinishFileTransferCallback(fileSize)));
}
}
/// <summary>
/// Finishes the transfer process by resetting some UI elements, clearing memory, and if enabled by the user, sends an email
/// </summary>
/// <param name="stoppedEarly">Indicates whether or not the transfer was stopped early by the user</param>
private void FinishTransfer(bool stoppedEarly = false)
{
StopTransferStatTimer();
//reset UI elements
transferSpeedLabel.Text = "Transfer Speed:";
estimatedTimeLabel.Text = "Estimated Time:";
dataTransferedLabel.Text = "Data Transfered:";
backupProgressBar.Value = 100;
//clear transfer stat memory
currentFilePathStat = null;
lastFileSizeStat = 0;
totalTransferedFileSizeStat = 0;
totalFileSizeStat = 0;
currentTransferedFileSizeStat = 0;
transferSpeedHistoryListStat.Clear();
//send email if required
if (Settings.data.useEmail)
{
if (isSendingEmail && smtpClient != null)
{
smtpClient.SendAsyncCancel();
}
else
{
SendBackupFinishedEmail(stoppedEarly);
}
}
else
{
FinishBackup();
}
}
/// <summary>
/// Finishes the backup process by resetting some UI elements to allow a new backup to start, displaying errors generated during the backup to the user, or automatically closing the program if it was supplied with args at run time
/// </summary>
private void FinishBackup()
{
//calculate time taken to backup everything
TimeSpan timeTaken = DateTime.Now - backupStartTime;
Log.WriteLine("Total duration: " + TimeSpanToFormattedString(timeTaken));
Log.WriteLine("--Backup finished--");
//reset UI elements
backupButton.Text = "Start Backup";
backupIsRunning = false;
backupThread = null;
backupStartTime = new DateTime();
//automatically close the program if the 'scheduledRun' argument was supplied and 'scheduleAutoClose' is set
if (autoRun && Settings.data.scheduleAutoClose)
{
Close();
}
else
{
string errorString = Log.GetSessionErrorsString();
if (!string.IsNullOrEmpty(errorString))
{
//show the user all errors that were accumulated during backup
errorString = Environment.NewLine + "Backup finished with the following error(s):" + Environment.NewLine + errorString;
AppendInfoTextBoxText(errorString);
if (!autoRun)
{
MessageBox.Show(errorString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
//clear error memory
Log.ClearSessionErrors();
}
/// <summary>
/// Used to stop a backup while it is currently running
/// </summary>
private void StopBackupEarly()
{
Log.WriteLine("Stopping backup early");
StopTransferStatTimer();
//abort the backup thread
if (backupThread != null)
{
backupThread.Abort();
//wait for thread to be aborted (or maxThreadAbortWaitTime reached)
int timeCounter = 0;
while (backupThread.ThreadState != ThreadState.AbortRequested && timeCounter < maxThreadAbortWaitTime)
{
timeCounter += 100;
Thread.Sleep(100);
}
}
//delete partially written file & the folder that contains it, if its empty
if (!string.IsNullOrEmpty(currentFilePathStat) && File.Exists(currentFilePathStat))
{
Log.WriteLine("Deleting partially written file: " + currentFilePathStat);
try
{
File.Delete(currentFilePathStat);
}
catch (Exception e)
{
Log.WriteLine("Couldn't delete partially written file: " + currentFilePathStat + ". " + e.Message, isError: true);
}
try
{
//check that the directory is empty
if (Directory.GetFiles(Path.GetDirectoryName(currentFilePathStat)).Length == 0 && Directory.GetDirectories(Path.GetDirectoryName(currentFilePathStat)).Length == 0)
{
Log.WriteLine("Deleting empty folder: " + Path.GetDirectoryName(currentFilePathStat));
Directory.Delete(Path.GetDirectoryName(currentFilePathStat));
}
}
catch (Exception e)
{
Log.WriteLine("Couldn't delete empty directory: " + Path.GetDirectoryName(currentFilePathStat) + ". " + e.Message, isError: true);
}
}
FinishTransfer(true);
}
/// <summary>
/// Renames backup folders which need to be updated with the latest DateTime
/// </summary>
/// <param name="backupFolderUpdateList">A list containing all the backup folders which need to be updated</param>
private void UpdateBackupFolderNames(ref List<Tuple<string, string>> backupFolderUpdateList)
{
string dstPath;
string backupName;
string dstFullPath;
string dstNewPath;
//update overwritten backup folder names with the latest date time
for (int i = 0; i < backupFolderUpdateList.Count; i++)
{
try
{
dstPath = backupFolderUpdateList[i].Item1;
backupName = backupFolderUpdateList[i].Item2;
dstFullPath = Path.Combine(dstPath, backupName);
dstNewPath = Path.Combine(dstPath, GetNewBackupFolderName());
if (dstFullPath != dstNewPath)
{
Directory.Move(dstFullPath, dstNewPath);
Directory.SetLastWriteTime(dstNewPath, DateTime.Now);
}
}
catch (Exception e)
{
Log.WriteLine("Couldn't update the backup folder name with the latest date and time. Please close the backup folder in any open programs and retry backing up. " + e.Message, isError: true);
}
}
}
/// <summary>
/// Finds the oldest backup within the specified folder path
/// </summary>
/// <param name="folderPath">The directory path</param>
/// <returns>The folder name of the oldest backup directory, or null if no backup directory is found</returns>