Files
EpisodeRenamer/Program.cs
2025-06-23 21:17:26 +07:00

133 lines
4.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
class EpisodeRenamer
{
// Паттерны для поиска номера эпизода (регулярные выражения + правила обработки)
private static readonly List<Pattern> patterns = new List<Pattern>
{
new Pattern(new Regex(@"\[\d+\]"), 1, -1),
new Pattern(new Regex(@"[s]\d+[e]\d+", RegexOptions.IgnoreCase), 4, null),
new Pattern(new Regex(@"[s]\d+[.][e]\d+", RegexOptions.IgnoreCase), 5, null),
new Pattern(new Regex(@"\d+$"), 0, null)
};
// Поддерживаемые расширения файлов
private static readonly HashSet<string> extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
".mkv", ".avi", ".mp4"
};
private class Pattern
{
public Regex Regex { get; }
public int? Start { get; }
public int? End { get; }
public Pattern(Regex regex, int? start, int? end)
{
Regex = regex;
Start = start;
End = end;
}
}
static void Main()
{
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine("\nВыход из программы.");
Environment.Exit(0);
};
Console.WriteLine("Чтобы оставить текущую директорию нажмите 'Enter'");
Console.WriteLine("Чтобы выйти нажмите 'Ctrl + C'");
while (true)
{
try
{
Console.Write("\nВведите путь до папки с эпизодами: ");
string input = Console.ReadLine()?.Trim() ?? string.Empty;
string folder = string.IsNullOrEmpty(input)
? Directory.GetCurrentDirectory()
: Path.GetFullPath(input);
if (Directory.Exists(folder))
{
ProcessFolder(folder);
}
else
{
Console.WriteLine("Указанная папка не существует.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка: {ex.Message}");
}
}
}
private static void ProcessFolder(string folder)
{
foreach (string filePath in Directory.GetFiles(folder))
{
string fileName = Path.GetFileName(filePath);
string extension = Path.GetExtension(fileName);
if (extensions.Contains(extension))
{
RenameFile(filePath, fileName, folder);
}
}
}
private static void RenameFile(string filePath, string fileName, string folder)
{
string nameWithoutExt = Path.GetFileNameWithoutExtension(fileName);
foreach (var pattern in patterns)
{
Match match = pattern.Regex.Match(nameWithoutExt);
if (!match.Success) continue;
string found = match.Value;
int startIndex = AdjustIndex(pattern.Start, found.Length);
int endIndex = AdjustIndex(pattern.End, found.Length);
if (startIndex < 0 || endIndex < 0 || startIndex >= endIndex)
continue;
string numberStr = found.Substring(
startIndex,
endIndex - startIndex
);
if (int.TryParse(numberStr, out int episode))
{
string newName = $"{episode:D2}{Path.GetExtension(fileName)}";
string newPath = Path.Combine(folder, newName);
if (!File.Exists(newPath))
{
File.Move(filePath, newPath);
Console.WriteLine($"\"{fileName}\" успешно переименован в \"{newName}\".");
return;
}
Console.WriteLine($"Ошибка: файл \"{newName}\" уже существует.");
}
}
}
private static int AdjustIndex(int? index, int length)
{
if (!index.HasValue) return length;
if (index.Value < 0) return length + index.Value;
return index.Value;
}
}