-
-
Notifications
You must be signed in to change notification settings - Fork 591
Expand file tree
/
Copy pathFilesFolders.cs
More file actions
522 lines (475 loc) · 19.3 KB
/
FilesFolders.cs
File metadata and controls
522 lines (475 loc) · 19.3 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
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
#pragma warning disable IDE0005
using System.Windows;
#pragma warning restore IDE0005
namespace Flow.Launcher.Plugin.SharedCommands
{
/// <summary>
/// Commands that are useful to run on files... and folders!
/// </summary>
public static class FilesFolders
{
private const string FileExplorerProgramName = "explorer";
/// <summary>
/// Copies the folder and all of its files and folders
/// including subfolders to the target location
/// </summary>
/// <param name="sourcePath"></param>
/// <param name="targetPath"></param>
/// <param name="messageBoxExShow"></param>
public static void CopyAll(this string sourcePath, string targetPath, Func<string, MessageBoxResult> messageBoxExShow = null)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourcePath);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourcePath);
}
try
{
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(targetPath, file.Name);
file.CopyTo(temppath, false);
}
// Recursively copy subdirectories by calling itself on each subdirectory until there are no more to copy
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(targetPath, subdir.Name);
CopyAll(subdir.FullName, temppath, messageBoxExShow);
}
}
catch (Exception)
{
#if DEBUG
throw;
#else
messageBoxExShow ??= MessageBox.Show;
messageBoxExShow(string.Format("Copying path {0} has failed, it will now be deleted for consistency", targetPath));
RemoveFolderIfExists(targetPath, messageBoxExShow);
#endif
}
}
/// <summary>
/// Check if the files and directories are identical between <paramref name="fromPath"/>
/// and <paramref name="toPath"/>
/// </summary>
/// <param name="fromPath"></param>
/// <param name="toPath"></param>
/// <param name="messageBoxExShow"></param>
/// <returns></returns>
public static bool VerifyBothFolderFilesEqual(this string fromPath, string toPath, Func<string, MessageBoxResult> messageBoxExShow = null)
{
try
{
var fromDir = new DirectoryInfo(fromPath);
var toDir = new DirectoryInfo(toPath);
if (fromDir.GetFiles("*", SearchOption.AllDirectories).Length != toDir.GetFiles("*", SearchOption.AllDirectories).Length)
return false;
if (fromDir.GetDirectories("*", SearchOption.AllDirectories).Length != toDir.GetDirectories("*", SearchOption.AllDirectories).Length)
return false;
return true;
}
catch (Exception)
{
#if DEBUG
throw;
#else
messageBoxExShow ??= MessageBox.Show;
messageBoxExShow(string.Format("Unable to verify folders and files between {0} and {1}", fromPath, toPath));
return false;
#endif
}
}
/// <summary>
/// Deletes a folder if it exists
/// </summary>
/// <param name="path"></param>
/// <param name="messageBoxExShow"></param>
public static void RemoveFolderIfExists(this string path, Func<string, MessageBoxResult> messageBoxExShow = null)
{
try
{
if (Directory.Exists(path))
Directory.Delete(path, true);
}
catch (Exception)
{
#if DEBUG
throw;
#else
messageBoxExShow ??= MessageBox.Show;
messageBoxExShow(string.Format("Not able to delete folder {0}, please go to the location and manually delete it", path));
#endif
}
}
/// <summary>
/// Attempts to delete a directory robustly with retry logic for locked files.
/// This method tries to delete files individually with retries, then removes empty directories.
/// Returns true if the directory was completely deleted, false if some files/folders remain.
/// </summary>
/// <param name="path">The directory path to delete</param>
/// <param name="maxRetries">Maximum number of retry attempts for locked files (default: 3)</param>
/// <param name="retryDelayMs">Delay in milliseconds between retries (default: 100ms)</param>
/// <returns>True if directory was fully deleted, false if some items remain</returns>
public static bool TryDeleteDirectoryRobust(string path, int maxRetries = 3, int retryDelayMs = 100)
{
if (!Directory.Exists(path))
return true;
bool fullyDeleted = true;
try
{
// First, try to delete all files in the directory tree
var files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
foreach (var file in files)
{
bool fileDeleted = false;
for (int attempt = 0; attempt <= maxRetries; attempt++)
{
try
{
// Remove read-only attribute if present
var fileInfo = new FileInfo(file);
if (fileInfo.Exists && fileInfo.IsReadOnly)
{
fileInfo.IsReadOnly = false;
}
File.Delete(file);
fileDeleted = true;
break;
}
catch (UnauthorizedAccessException)
{
// File is in use or access denied, wait and retry
if (attempt < maxRetries)
{
System.Threading.Thread.Sleep(retryDelayMs);
}
}
catch (IOException)
{
// File is in use, wait and retry
if (attempt < maxRetries)
{
System.Threading.Thread.Sleep(retryDelayMs);
}
}
catch
{
// Other exceptions, don't retry
break;
}
}
if (!fileDeleted)
{
fullyDeleted = false;
}
}
// Then, try to delete all empty directories (from deepest to shallowest)
var directories = Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
.OrderByDescending(d => d.Length) // Delete deeper directories first
.ToArray();
foreach (var directory in directories)
{
try
{
if (Directory.Exists(directory) && !Directory.EnumerateFileSystemEntries(directory).Any())
{
Directory.Delete(directory, false);
}
}
catch
{
// If we can't delete an empty directory, mark as not fully deleted
fullyDeleted = false;
}
}
// Finally, try to delete the root directory itself
try
{
if (Directory.Exists(path) && !Directory.EnumerateFileSystemEntries(path).Any())
{
Directory.Delete(path, false);
}
else if (Directory.Exists(path))
{
fullyDeleted = false;
}
}
catch
{
fullyDeleted = false;
}
}
catch
{
fullyDeleted = false;
}
return fullyDeleted;
}
/// <summary>
/// Checks if a directory exists
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool LocationExists(this string path)
{
return Directory.Exists(path);
}
/// <summary>
/// Checks if a file exists
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool FileExists(this string filePath)
{
return File.Exists(filePath);
}
/// <summary>
/// Checks if a file or directory exists
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool FileOrLocationExists(this string path)
{
return LocationExists(path) || FileExists(path);
}
/// <summary>
/// Open a directory window (using the OS's default handler, usually explorer)
/// </summary>
/// <param name="fileOrFolderPath"></param>
/// <param name="messageBoxExShow"></param>
public static void OpenPath(string fileOrFolderPath, Func<string, MessageBoxResult> messageBoxExShow = null)
{
var psi = new ProcessStartInfo
{
FileName = FileExplorerProgramName,
UseShellExecute = true,
Arguments = '"' + fileOrFolderPath + '"'
};
try
{
if (LocationExists(fileOrFolderPath) || FileExists(fileOrFolderPath))
Process.Start(psi);
}
catch (Exception)
{
#if DEBUG
throw;
#else
messageBoxExShow ??= MessageBox.Show;
messageBoxExShow(string.Format("Unable to open the path {0}, please check if it exists", fileOrFolderPath));
#endif
}
}
/// <summary>
/// Open a file with associated application
/// </summary>
/// <param name="filePath">File path</param>
/// <param name="workingDir">Working directory</param>
/// <param name="asAdmin">Open as Administrator</param>
/// <param name="messageBoxExShow"></param>
public static void OpenFile(string filePath, string workingDir = "", bool asAdmin = false, Func<string, MessageBoxResult> messageBoxExShow = null)
{
var psi = new ProcessStartInfo
{
FileName = filePath,
UseShellExecute = true,
WorkingDirectory = workingDir,
Verb = asAdmin ? "runas" : string.Empty
};
try
{
if (FileExists(filePath))
Process.Start(psi);
}
catch (Exception)
{
#if DEBUG
throw;
#else
messageBoxExShow ??= MessageBox.Show;
messageBoxExShow(string.Format("Unable to open the path {0}, please check if it exists", filePath));
#endif
}
}
///<summary>
/// This checks whether a given string is a zip file path.
/// By default does not check if the zip file actually exist on disk, can do so by
/// setting checkFileExists = true.
///</summary>
public static bool IsZipFilePath(string querySearchString, bool checkFileExists = false)
{
if (IsLocationPathString(querySearchString) && querySearchString.Split('.').Last() == "zip")
{
if (checkFileExists)
return FileExists(querySearchString);
return true;
}
return false;
}
///<summary>
/// This checks whether a given string is a directory path or network location string.
/// It does not check if location actually exists.
///</summary>
public static bool IsLocationPathString(this string querySearchString)
{
if (string.IsNullOrEmpty(querySearchString) || querySearchString.Length < 3)
return false;
// // shared folder location, and not \\\location\
if (querySearchString.StartsWith(@"\\")
&& querySearchString[2] != '\\')
return true;
// c:\
if (char.IsLetter(querySearchString[0])
&& querySearchString[1] == ':'
&& querySearchString[2] == '\\')
{
return querySearchString.Length == 3 || querySearchString[3] != '\\';
}
return false;
}
///<summary>
/// Gets the previous level directory from a path string.
/// Checks that previous level directory exists and returns it
/// as a path string, or empty string if doesn't exist
///</summary>
public static string GetPreviousExistingDirectory(Func<string, bool> locationExists, string path)
{
var index = path.LastIndexOf('\\');
if (index > 0 && index < (path.Length - 1))
{
string previousDirectoryPath = path[..(index + 1)];
return locationExists(previousDirectoryPath) ? previousDirectoryPath : string.Empty;
}
else
{
return string.Empty;
}
}
///<summary>
/// Returns the previous level directory if path incomplete (does not end with '\').
/// Does not check if previous level directory exists.
/// Returns passed in string if is complete path
///</summary>
public static string ReturnPreviousDirectoryIfIncompleteString(string path)
{
if (!path.EndsWith("\\"))
{
// not full path, get previous level directory string
var indexOfSeparator = path.LastIndexOf('\\');
return path[..(indexOfSeparator + 1)];
}
return path;
}
/// <summary>
/// Returns if <paramref name="parentPath"/> contains <paramref name="subPath"/>. Equal paths are not considered to be contained by default.
/// From https://stackoverflow.com/a/66877016
/// </summary>
/// <param name="parentPath">Parent path</param>
/// <param name="subPath">Sub path</param>
/// <param name="allowEqual">If <see langword="true"/>, when <paramref name="parentPath"/> and <paramref name="subPath"/> are equal, returns <see langword="true"/></param>
/// <returns></returns>
public static bool PathContains(string parentPath, string subPath, bool allowEqual = false)
{
var rel = Path.GetRelativePath(parentPath.EnsureTrailingSlash(), subPath);
return (rel != "." || allowEqual)
&& rel != ".."
&& !rel.StartsWith("../")
&& !rel.StartsWith(@"..\")
&& !Path.IsPathRooted(rel);
}
/// <summary>
/// Returns path ended with "\"
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string EnsureTrailingSlash(this string path)
{
return path.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
}
/// <summary>
/// Validates a directory, creating it if it doesn't exist
/// </summary>
/// <param name="path"></param>
public static void ValidateDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
/// <summary>
/// Validates a data directory, synchronizing it by ensuring all files from a bundled source directory exist in it.
/// If files are missing or outdated, they are copied from the bundled directory to the data directory.
/// </summary>
/// <param name="bundledDataDirectory"></param>
/// <param name="dataDirectory"></param>
public static void ValidateDataDirectory(string bundledDataDirectory, string dataDirectory)
{
if (!Directory.Exists(dataDirectory))
{
Directory.CreateDirectory(dataDirectory);
}
foreach (var bundledDataPath in Directory.GetFiles(bundledDataDirectory))
{
var data = Path.GetFileName(bundledDataPath);
if (data == null) continue;
var dataPath = Path.Combine(dataDirectory, data);
if (!File.Exists(dataPath))
{
File.Copy(bundledDataPath, dataPath);
}
else
{
var time1 = new FileInfo(bundledDataPath).LastWriteTimeUtc;
var time2 = new FileInfo(dataPath).LastWriteTimeUtc;
if (time1 != time2)
{
File.Copy(bundledDataPath, dataPath, true);
}
}
}
}
/// <summary>
/// Resolves a path that may be relative to an absolute path.
/// If the path is already absolute, returns it as-is.
/// If the path is not rooted (as determined by <see cref="Path.IsPathRooted(string)"/>), resolves it relative to ProgramDirectory.
/// </summary>
/// <param name="path">The path to resolve</param>
/// <returns>An absolute path</returns>
public static string ResolveAbsolutePath(string path)
{
if (string.IsNullOrEmpty(path))
return path;
// If already absolute, return as-is
if (Path.IsPathFullyQualified(path))
return path;
// Resolve relative to ProgramDirectory, handling invalid path formats gracefully
try
{
return Path.GetFullPath(Path.Combine(Directory.GetParent(Assembly.GetExecutingAssembly().Location).ToString(), path));
}
catch (Exception)
{
// If the path cannot be resolved (invalid characters, format, or too long),
// return the original path to avoid crashing the application.
return path;
}
}
}
}