Implemented the ability to flatten directories, esp useful with nested folders in archives.
This commit is contained in:
parent
56e8a0059e
commit
7f404a0ce9
7 changed files with 91 additions and 22 deletions
|
@ -1,11 +1,65 @@
|
|||
namespace API.Extensions
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace API.Extensions
|
||||
{
|
||||
public static class DirectoryInfoExtensions
|
||||
{
|
||||
public static void Empty(this System.IO.DirectoryInfo directory)
|
||||
public static void Empty(this DirectoryInfo directory)
|
||||
{
|
||||
foreach(System.IO.FileInfo file in directory.EnumerateFiles()) file.Delete();
|
||||
foreach(System.IO.DirectoryInfo subDirectory in directory.EnumerateDirectories()) subDirectory.Delete(true);
|
||||
foreach(FileInfo file in directory.EnumerateFiles()) file.Delete();
|
||||
foreach(DirectoryInfo subDirectory in directory.EnumerateDirectories()) subDirectory.Delete(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flattens all files in subfolders to the passed directory recursively.
|
||||
///
|
||||
///
|
||||
/// foo<para />
|
||||
/// ├── 1.txt<para />
|
||||
/// ├── 2.txt<para />
|
||||
/// ├── 3.txt<para />
|
||||
/// ├── 4.txt<para />
|
||||
/// └── bar<para />
|
||||
/// ├── 1.txt<para />
|
||||
/// ├── 2.txt<para />
|
||||
/// └── 5.txt<para />
|
||||
///
|
||||
/// becomes:<para />
|
||||
/// foo<para />
|
||||
/// ├── 1.txt<para />
|
||||
/// ├── 2.txt<para />
|
||||
/// ├── 3.txt<para />
|
||||
/// ├── 4.txt<para />
|
||||
/// ├── bar_1.txt<para />
|
||||
/// ├── bar_2.txt<para />
|
||||
/// └── bar_5.txt<para />
|
||||
/// </summary>
|
||||
/// <param name="directory"></param>
|
||||
public static void Flatten(this DirectoryInfo directory)
|
||||
{
|
||||
FlattenDirectory(directory, directory);
|
||||
}
|
||||
|
||||
private static void FlattenDirectory(DirectoryInfo root, DirectoryInfo directory)
|
||||
{
|
||||
if (!root.FullName.Equals(directory.FullName)) // I might be able to replace this with root === directory
|
||||
{
|
||||
foreach (var file in directory.EnumerateFiles())
|
||||
{
|
||||
if (file.Directory == null) continue;
|
||||
var newName = $"{file.Directory.Name}_{file.Name}";
|
||||
var newPath = Path.Join(root.FullName, newName);
|
||||
Console.WriteLine($"Renaming/Moving file to: {newPath}");
|
||||
file.MoveTo(newPath);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var subDirectory in directory.EnumerateDirectories())
|
||||
{
|
||||
FlattenDirectory(root, subDirectory);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue