Skip to content

Instantly share code, notes, and snippets.

@bittercoder
Created January 28, 2019 02:37
Show Gist options
  • Save bittercoder/ab976e81ed0a4239169bf9f1dbcfc53b to your computer and use it in GitHub Desktop.
Save bittercoder/ab976e81ed0a4239169bf9f1dbcfc53b to your computer and use it in GitHub Desktop.
C# program to arrange movies into folders, then those folders in groups by first letter (A-Z...)
using System;
using System.IO;
using System.Linq;
namespace FileArranger
{
class Program
{
static void Main(string[] args)
{
var path = @"\\diskstation\movies";
var arranger = new MovieArranger(path);
arranger.Execute();
Console.WriteLine("Press any key");
Console.ReadKey();
}
}
public class MovieArranger
{
public bool Simulation { get; set; }
public string Path { get; private set; }
public MovieArranger(string path)
{
Path = path;
}
public void Execute()
{
MoveFilesIntoDirectories();
MoveDirectoriesIntoParentLetterDirectory();
}
void MoveDirectoriesIntoParentLetterDirectory()
{
var parentDirectory = new DirectoryInfo(Path);
var directoriesByLetter = parentDirectory.EnumerateDirectories()
.Where(x=>!x.Name.StartsWith("."))
.ToLookup(x => char.ToUpperInvariant(x.Name[0]).ToString(), x => x);
foreach (var letter in directoriesByLetter)
{
var newDirectory = parentDirectory.CreateSubdirectory(letter.Key);
foreach (var directory in letter)
{
MoveDirectory(directory, newDirectory);
}
}
}
private void MoveDirectory(DirectoryInfo directory, DirectoryInfo target)
{
if (directory.FullName == target.FullName) return;
Console.WriteLine($"Move: {directory.FullName} => {target.FullName}");
if (Simulation)
{
Console.WriteLine("Skipping - simulation");
return;
}
directory.MoveTo(System.IO.Path.Combine(target.FullName, directory.Name));
}
void MoveFilesIntoDirectories()
{
foreach (var file in Directory.GetFiles(Path).Select(x => new FileInfo(x)))
{
if (file.Name.StartsWith("."))
{
Console.WriteLine($"Skipping file starting with period: {file.FullName}");
continue;
}
var directoryName = file.Name.Replace(file.Extension, "").Replace(".", " ");
var newDirectory = Directory.CreateDirectory(System.IO.Path.Combine(Path, directoryName));
MoveFileToDirectory(file, newDirectory);
}
}
void MoveFileToDirectory(FileInfo file, DirectoryInfo target)
{
var targetPath = System.IO.Path.Combine(target.FullName, file.Name);
Console.WriteLine($"Move: {file.FullName} => {targetPath}");
if (Simulation)
{
Console.WriteLine("Skipping - simulation");
return;
}
file.MoveTo(targetPath);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment