-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataBackupper.cs
99 lines (82 loc) · 3.2 KB
/
DataBackupper.cs
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
using MediaDevices;
using System;
using System.IO;
namespace GarminMtpDataBackupper
{
public class DataBackupper
{
private readonly Config.Config _config;
private readonly Device _device;
private string GarminRootPath => Path.Combine(_config.GarminDiskName, _config.GarminRoot);
private string FormattedCurrentDate => DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
private string DestinationRootFolderPath => Path.Combine(_config.TargetPath, $"{_config.GarminDeviceName}_{FormattedCurrentDate}");
private int _directoriesCount;
private int _filesCount;
public DataBackupper(Config.Config config, Device device)
{
_config = config;
_device = device;
_directoriesCount = 0;
_filesCount = 0;
}
public void BackupGarminData()
{
var garminRootPath = GarminRootPath;
var destinationRootPath = DestinationRootFolderPath;
using (_device)
{
_device.Connect();
foreach (var folderName in _config.GarminFolders)
{
string sourcePath = Path.Combine(garminRootPath, folderName);
string destinationPath = Path.Combine(destinationRootPath, folderName);
Logger.Info($@"Copying folder FROM: {sourcePath} TO: {destinationPath}");
CopyDirectoryRecursively(sourcePath, destinationPath);
}
_device.Disconnect();
}
PrintCopiesCount();
}
private void CopyDirectoryRecursively(string sourcePath, string destinationPath)
{
if (!_device.FolderExists(sourcePath))
{
Logger.Error($"Missing source: {sourcePath}");
return;
}
MediaDirectoryInfo sourceDirectoryInfo;
try
{
sourceDirectoryInfo = _device.GetDirectoryInfo(sourcePath);
}
catch (Exception exception)
{
Logger.Error($"Missing source or is not accessible: {sourcePath}", exception);
return;
}
if (!Directory.Exists(destinationPath))
{
Directory.CreateDirectory(destinationPath);
}
var files = sourceDirectoryInfo.EnumerateFiles();
foreach (var file in files)
{
string temppath = Path.Combine(destinationPath, file.Name);
file.CopyTo(temppath, false);
_filesCount++;
}
var folders = sourceDirectoryInfo.EnumerateDirectories();
foreach (var subdir in folders)
{
string temppath = Path.Combine(destinationPath, subdir.Name);
Logger.Warning($@"Copying SUBfolder FROM: {sourcePath} TO: {destinationPath}");
CopyDirectoryRecursively(subdir.FullName, temppath);
_directoriesCount++;
}
}
private void PrintCopiesCount()
{
Logger.Info($"Copied\n\t- Directories: {_directoriesCount}\n\t- Files: {_filesCount}");
}
}
}