-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileOperations.cs
127 lines (115 loc) · 4.01 KB
/
FileOperations.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
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
using System;
using System.Collections.Generic;
using System.IO;
namespace RandomFiles
{
class FileOperations
{
public int DoneFilesCount { get; private set; }
public string CurrentFile { get; private set; }
public long DoneFilesSize { get; private set; }
public string Source { get; set; }
public bool KeepEmptyFolders { get; set; }
public FileOperations()
{
DoneFilesCount = 0;
CurrentFile = "";
DoneFilesSize = 0;
}
public void DeleteFiles(List<FileItem> files)
{
DoneFilesCount = 0;
DoneFilesSize = 0;
var output = new Output();
files.ForEach((Action<FileItem>)(item =>
{
try
{
CurrentFile = item.Path;
File.Delete(item.Path);
if (!KeepEmptyFolders)
{
var dir = Path.GetDirectoryName(item.Path);
while (dir != Source)
{
bool empty =
Directory.GetFiles(
dir, "",
SearchOption.AllDirectories).Length < 1;
if (empty)
{
Directory.Delete(dir, true);
}
dir = Path.GetFullPath(Path.Combine(dir, ".."));
}
}
}
catch (Exception ex)
{
output.Error($"File: {Path.GetFileName(item.Path)} - " +
ex.Message);
}
finally
{
DoneFilesCount++;
DoneFilesSize += item.Size;
}
}));
}
/// <summary>
/// Copies the files to the destination
/// </summary>
/// <param name="files">List of files to be copied</param>
/// <param name="destination">The destination path</param>
/// <param name="sameFolder">
/// Copy all files in the same folder if true
/// Or make the folder structure based on source path of files if false.
/// </param>
/// <param name="sourcePath">
/// If sameFolder is false, this path will be used as root for making
/// folder structure in the destination.
/// </param>
public void CopyFiles(
List<FileItem> files,
string destination,
bool sameFolder,
string sourcePath = "")
{
DoneFilesCount = 0;
DoneFilesSize = 0;
var output = new Output();
files.ForEach((Action<FileItem>)(item =>
{
try
{
CurrentFile = item.Path;
string destDir = destination;
if (!sameFolder)
{
string relativeDestDir = Path.GetRelativePath(
sourcePath, Path.GetDirectoryName(item.Path));
destDir = Path.Combine(destination, relativeDestDir);
if (!Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
}
File.Copy(item.Path,
Path.Combine(
destDir,
Path.GetFileName(item.Path)));
}
catch (Exception ex)
{
output.Error($"File: {Path.GetFileName(item.Path)} - " +
ex.Message);
}
finally
{
DoneFilesCount++;
DoneFilesSize += item.Size;
}
}));
}
}
}