-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDuplicatesAnalyzer.cs
212 lines (180 loc) · 6.53 KB
/
DuplicatesAnalyzer.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
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
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Security.Cryptography;
namespace FilesDuplicatesAnalyzer
{
public class DuplicatesAnalyzer
{
public string[] AlanyzeImages(string pathFiles, string fileTypes, SearchOption searchOptionType)
{
if(!Directory.Exists(pathFiles))
{
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + $" directorio especificado no existe: {pathFiles}");
throw new DirectoryNotFoundException("El directorio especificado no existe.");
}
List<string> result = new();
Dictionary<string, string> fileHashes = new();
try
{
string[] files;
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + "******************************************");
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + "* Process Started");
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + "******************************************");
if(!string.IsNullOrEmpty(fileTypes))
{
string[] fileExtensions = fileTypes.Split(',');
List<string> filteredFiles = new List<string>();
foreach(string extension in fileExtensions)
{
filteredFiles.AddRange(Directory.GetFiles(pathFiles, "*." + extension.Trim(), searchOptionType));
}
files = filteredFiles.ToArray();
}
else
{
files = Directory.GetFiles(pathFiles, "*.*", searchOptionType);
}
foreach(string file in files)
{
if(!File.Exists(file))
{
// El archivo no existe, se omite su procesamiento
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + $" :::! archivo no existe: {file}");
continue;
}
string fileHash = CalculateFileHash(file);
if(fileHashes.ContainsValue(fileHash))
{
string originalFile = fileHashes.FirstOrDefault(x => x.Value == fileHash).Key;
result.Add(originalFile + " | " + file);
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + $" ::: Original: {originalFile} | Duplicado: {file}");
}
else
{
fileHashes.Add(file, fileHash);
}
}
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + "******************************************");
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + "* Process Finished");
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + "******************************************");
}
catch(UnauthorizedAccessException ex)
{
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + $" Exception(ux): {ex.Message}");
throw new UnauthorizedAccessException("No se tiene acceso para leer uno o más archivos en el directorio especificado.", ex);
}
catch(Exception ex)
{
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + $" Exception(ex): {ex.Message}");
throw new Exception("Ocurrió un error al analizar las imágenes.", ex);
}
return result.ToArray();
}
private string CalculateFileHash(string filePath)
{
using(var sha256 = SHA256.Create())
{
try
{
using(var stream = File.OpenRead(filePath))
{
byte[] hashBytes = sha256.ComputeHash(stream);
return BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
}
}
catch(Exception ex)
{
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + $" Exception(ex): {ex.Message}");
throw new Exception("Ocurrió un error al calcular el hash del archivo: " + filePath, ex);
}
}
}
public string[] FindDuplicateFiles(string folderPath, string[] extensions, SearchOption searchOptionType)
{
Dictionary<string, List<string>> filesByHash = new();
HashSet<string> duplicateFiles = new();
List<string> tempDuplicateFiles = new();
List<string> duplicateFilesAndHush = new();
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + " Process Started");
foreach(var extension in extensions)
{
string[] files = Directory.GetFiles(folderPath, $"*.{extension}", searchOptionType);
foreach(var file in files)
{
if(File.Exists(file))
{
string hash = GetFileHash(file);
duplicateFilesAndHush.Add(file + " " + hash);
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + $" {file + " " + hash}");
if(!filesByHash.ContainsKey(hash))
{
filesByHash[hash] = new List<string>();
}
else
{
tempDuplicateFiles.Add(file);
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + $" Duplicated file found: {file}");
}
filesByHash[hash].Add(file);
}
}
}
duplicateFiles.UnionWith(tempDuplicateFiles); // Agregar los archivos duplicados encontrados a la lista final
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + " ");
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + " Process Finished");
return duplicateFiles.ToArray();
}
private string GetFileHash(string filePath)
{
using(var sha256 = SHA256.Create())
{
using(var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
byte[] hashBytes = sha256.ComputeHash(stream);
return BitConverter.ToString(hashBytes).Replace("-", string.Empty);
}
}
}
public string[] FindDuplicateFilesV01(string folderPath, string[] extensions, SearchOption SearchOptionType)
{
Dictionary<string, List<string>> filesByHash = new();
List<string> duplicateFiles = new();
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + " Process Started");
foreach(var extension in extensions)
{
string[] files = Directory.GetFiles(folderPath, $"*.{extension}", SearchOptionType);
foreach(var file in files)
{
if (File.Exists(file))
{
string hash = GetFileHash(file);
if(!filesByHash.ContainsKey(hash))
{
filesByHash[hash] = new List<string>();
}
else
{
duplicateFiles.AddRange(filesByHash[hash]);
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + $" duplicated file founded: {file}");
}
filesByHash[hash].Add(file);
}
}
}
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + " ");
Debug.WriteLine(DateTime.Now.ToString("yyyy/dd/MM HH:mm:ss") + " Process Finished");
return duplicateFiles.ToArray();
}
private string GetFileHashV01(string filePath)
{
using(var md5 = MD5.Create())
{
using(var stream = File.OpenRead(filePath))
{
byte[] hashBytes = md5.ComputeHash(stream);
return BitConverter.ToString(hashBytes).Replace("-", string.Empty);
}
}
}
}
}