using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Chronos.Core.Diagnostics; using Chronos.Core.IO; using Chronos.Core.Localization; using Chronos.Core.Naming; namespace Chronos.Core.Archiving; /// /// What the planner needs to know about a sequence to rename it. Without its sidecar () the templates see /// the index row's capture time, camera and lens, and a sequence without a capture time keeps its folder and title. /// public sealed record RenameSubject(Guid SequenceId, string Folder, string? Title, DateTime? FirstCapture, string? CameraMake, string? CameraModel, string? Lens) { /// /// The sidecar, whose first frame the folder and title templates see as filing saw it, and the files beside its frames, /// which a file template renames (empty without one); null when it was not read, or could not be. /// public SequenceFiles? Files { get; init; } /// /// The sidecar could not be read, or belongs to another sequence: the sequence stays as it is, and so does every folder /// it is inside, which could not take it along (). /// public bool Unreadable { get; init; } } /// A sequence's sidecar as read for a plan, and every file in the folders of its frames (). public sealed record SequenceFiles(SequenceManifest Manifest, IReadOnlyCollection Present); /// /// One sequence's change: its folder, its title, the names of its files (Reorganize, owner review 2, R7), or several of /// them. A step that changes nothing lists only why: frames that keep their file names, or a sequence that stays as it is /// because its sidecar cannot be read (). /// /// The folder moves only because a folder it is inside moves (a sequence nested in another). public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried = false) { public bool MovesFolder => !string.Equals(FromFolder, ToFolder, StringComparison.Ordinal); public bool Retitles => !string.Equals(FromTitle, ToTitle, StringComparison.Ordinal); /// Whether applying the step changes anything: the folder, the title or file names. public bool Changes => MovesFolder || Retitles || FileChanges > 0; /// /// The new folder or file names come from the sequence's title (the folder or file template uses {title}): a title /// edited since the plan would leave them named after the old one. /// public bool NamedByTitle { get; init; } /// Whether what the step changes depends on the sequence's title: it changes it, or names the folder or files after it. public bool UsesTitle => Retitles || NamedByTitle; /// /// The sidecar's frames version the file names were planned at; 0 when no file gets a new name. What the apply checks the /// files by only in a plan journaled without . /// public int FramesVersion { get; init; } /// Frames whose file gets a new name (their companions follow them). public int FileChanges { get; init; } /// The first renamed frames (), old and new name relative to the sequence folder. public IReadOnlyList FileSamples { get; init; } = []; /// /// Every file rename of the step, as a digest (): the apply renames the files only /// while they plan to exactly these. Null when no file gets a new name (or in a plan journaled before it existed). /// public string? FileDigest { get; init; } /// Frames that keep their file names, and why; (0 frames) when the whole sequence stays as it is. public IReadOnlyList Blocked { get; init; } = []; } /// /// The templates of a Reorganize (owner review 2, R7): the folder ({title} = the new title), the file names and the /// title ({title} = the current title); null leaves that part as it is. /// public sealed record RenameTemplates(string? Folder = null, string? File = null, string? Title = null) { private static readonly NamingContext Sample = TemplateRules.Sample()[0]; public bool IsEmpty => Folder is null && File is null && Title is null; /// /// The first template that cannot be used, by its API name (folderTemplate, fileTemplate, /// titleTemplate): blank, not valid (), with a format a sample cannot be written /// with ({date:%}), expanding to nothing, or, for a folder or file template, breaking a rule of the archive's /// templates (: a folder scans never enter; a slash, a lost extension or names that would /// repeat); null when every one given can. The archive settings' templates are checked alike, except for the rules a /// template archive.json already holds breaks (ArchiveSettings.Problem). /// public string? Problem() => Check()?.Field; /// /// The first template that cannot be used (), with the rule of it breaks /// when it parses and expands (); null when every one given can. /// public TemplateProblem? Check() => Unusable("folderTemplate", Folder, t => t.ExpandFolder(Sample), TemplateRules.FolderRule) ?? Unusable("fileTemplate", File, t => t.ExpandFile(Sample), TemplateRules.FileRule) ?? Unusable("titleTemplate", Title, t => t.ExpandText(Sample)); private static TemplateProblem? Unusable(string field, string? template, Func expand, Func? rule = null) { if (template is null) return null; if (string.IsNullOrWhiteSpace(template)) return new TemplateProblem(field, null); var parsed = PathTemplate.Parse(template); if (!parsed.IsValid) return new TemplateProblem(field, null); try { if (expand(parsed).Length == 0) return new TemplateProblem(field, null); return rule?.Invoke(parsed) is { } broken ? new TemplateProblem(field, broken) : null; } catch (FormatException) { return new TemplateProblem(field, null); } } } /// /// A template that cannot be used: its API name (folderTemplate, fileTemplate, titleTemplate) and the /// rule of it breaks (ReservedFolder, FileSeparator, Extension, /// NotUnique, each explained by Errors.Template.<Rule>); no rule when it is blank, not valid or expands to nothing. /// public sealed record TemplateProblem(string Field, string? Rule); /// A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned. public sealed class NestedRenameException(string target, string folder) : ArgumentException(Loc.L("Archive.Error.NestedTarget", target, folder)) { public string Target { get; } = target; public string Folder { get; } = folder; } /// The exact changes a mass rename will make (its dry run); applying it makes exactly these. public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList Steps) { /// The file template the steps' file names come from; null when files keep their names. public string? FileTemplate { get; init; } /// /// The folder template the steps' folders come from; null when folders stay, or in a plan journaled before it was kept /// (whose steps' folders are then taken as planned). /// public string? FolderTemplate { get; init; } /// The title template the steps' titles come from; null when titles stay, or in a plan journaled before it was kept. public string? TitleTemplate { get; init; } /// The sequences the plan was made for, in the order they were given (the order that decides which new folder gets " (2)"). public IReadOnlyList Subjects { get; init; } = []; /// /// A digest of what the plan changes (its steps in order, as a dry run shows them, every file rename by its digest, and /// the file template), the same for two plans of the same archive state: what a confirmation sends back so the change /// made is the one that was shown. The frames version is not part of it: photos a sequence received since under the names /// the plan gives them (an upload filed with the same template) leave the plan as it was, and the apply renames the files /// only while they rename exactly as planned (). /// public string Fingerprint() { var text = new StringBuilder(FileTemplate).Append('\n'); foreach (var s in Steps) { text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FromFolder}|{s.ToFolder}|{s.FromTitle}|{s.ToTitle}|{s.Carried}|{s.FileChanges}|{s.FileDigest}|"); foreach (var sample in s.FileSamples) text.Append(sample.From).Append('>').Append(sample.To).Append(';'); foreach (var blocked in s.Blocked) text.Append(CultureInfo.InvariantCulture, $"{blocked.Reason}:{blocked.Frames};"); text.Append('\n'); } return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString()))); } } /// /// What the completed steps of a plan did, over every run that applied them (): the /// sequences changed, the frames whose file got a new name, and the sequences not changed as planned: because they changed /// since, left as they were (), their file names kept () or their title and file /// names kept (); their file names kept because a photo was in use or a new name was taken /// (); their title and file names kept because a newer Chronos wrote their sidecar (); /// left as they were because the folder around them that was to carry them stayed, for its own reason /// (). /// public sealed record RenameTally { public IReadOnlyList Changed { get; init; } = []; public int Files { get; init; } public IReadOnlyList Dropped { get; init; } = []; public IReadOnlyList FilesKept { get; init; } = []; public IReadOnlyList TitlesKept { get; init; } = []; public IReadOnlyList FilesBusy { get; init; } = []; public IReadOnlyList Newer { get; init; } = []; public IReadOnlyList CarriedKept { get; init; } = []; } /// A plan being applied, with the steps already completed; lets an interrupted rename resume (BRIEF §7). /// The job applying the plan was paused, cancelled or failed between two steps: an archive open leaves the /// plan to that job, which completes it when it is resumed or retried. public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList Completed, bool Held = false) { /// What the completed steps did, so a resumed run reports the whole plan. public RenameTally Done { get; init; } = new(); public static string PathFor(ArchivePaths archive, Guid planId) => Path.Combine(archive.JournalDirectory, $"rename-{planId:N}.json"); public static void Write(ArchivePaths archive, RenameJournal journal) { Directory.CreateDirectory(archive.JournalDirectory); AtomicFile.WriteAllBytes(PathFor(archive, journal.Plan.Id), JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJsonIndented.Default.RenameJournal)); } /// /// Journals left by interrupted renames, held ones included. A journal that cannot be read (damaged by hand, or by a /// disk) is logged and left where it is, so the archive still opens; its plan is not resumed, and the file renames of /// its steps are completed by their own journals (). /// public static IReadOnlyList ListPending(ArchivePaths archive) { if (!Directory.Exists(archive.JournalDirectory)) return []; var list = new List(); foreach (var path in Directory.EnumerateFiles(archive.JournalDirectory, "rename-*.json").Order(StringComparer.Ordinal)) { try { if (Parse(File.ReadAllBytes(path)) is { } journal) list.Add(journal); else Log.Warning("archive", $"The rename journal {Path.GetFileName(path)} is empty or incomplete; its plan is not resumed"); } catch (JsonException ex) { Log.Warning("archive", $"The rename journal {Path.GetFileName(path)} cannot be read; its plan is not resumed", ex); } } return list; } /// /// The journal of the plan ; null when there is none (the plan completed, or never started). /// Throws when the journal is there but cannot be read, so its job fails with the /// reason instead of planning again over a half-applied plan. /// public static RenameJournal? Read(ArchivePaths archive, Guid planId) { var path = PathFor(archive, planId); if (!File.Exists(path)) return null; try { return Parse(File.ReadAllBytes(path)) ?? throw new InvalidDataException($"The rename journal {Path.GetFileName(path)} is incomplete."); } catch (JsonException ex) { throw new InvalidDataException($"The rename journal {Path.GetFileName(path)} cannot be read.", ex); } } private static RenameJournal? Parse(byte[] bytes) => JsonSerializer.Deserialize(bytes, ArchiveJson.Default.RenameJournal) is { Plan: not null, Completed: not null } journal ? journal : null; public static void Delete(ArchivePaths archive, Guid planId) => File.Delete(PathFor(archive, planId)); } /// Builds rename plans from folder, title and file templates (BRIEF §7.1, §12.5; Reorganize, owner review 2, R7). public static class RenamePlanner { /// /// Expands (where {title} is the current title) and then /// (where {title} is the new title) for every subject, from its first frame as /// filing saw it (); a title is text, not a file /// name (). A target folder that is any current sequence folder, exists on disk or /// was given to an earlier subject (whatever its case) gets " (2)", " (3)"…; a sequence keeps its own folder in the /// template's case only while no other folder holds that exact name. With every /// subject's frames get their names from it as filing names them (, with the new title), /// counted and sampled in its step, and the frames that keep their names are listed there with the reason; a step whose /// new folder or file names come from {title} says so (). A subject /// whose sidecar could not be read (, or no for a /// file template) stays as it is, listed with the reason, and so does the folder of every subject it is inside. Null /// templates leave that part unchanged; subjects without a change produce no step, unless frames of theirs keep their /// names. A folder that moves takes the sequences inside it along: each gets a step after /// every move, so the index follows its files; a selected sequence inside a moving folder that moves elsewhere leaves first. /// /// Every sequence folder of the archive (renamed or not). /// The archive's other sequences inside a subject's folder, with their titles. /// Whether a folder of exactly that name, in every level's case, is on disk /// (): on a case-sensitive file system Trip (2) beside a sequence at trip (2) is /// another folder, which a change of case could never move onto; on a case-insensitive one only the sequence's own /// folder can be found, under at most one of the two names (under neither when the disk spells it another way, such as /// TRIP (2)). Null when no folder but the sequences' own counts. /// A target lies inside a sequence's folder, or inside another target. public static RenamePlan Plan(Guid archiveId, IReadOnlyList subjects, string? folderTemplate, string? titleTemplate, IEnumerable occupied, Func existsOnDisk, IReadOnlyList? nested = null, string? fileTemplate = null, Func? existsExactly = null) { existsExactly ??= _ => false; var folder = folderTemplate is null ? null : PathTemplate.Parse(folderTemplate); var title = titleTemplate is null ? null : PathTemplate.Parse(titleTemplate); var file = fileTemplate is null ? null : PathTemplate.Parse(fileTemplate); bool folderByTitle = folder?.Uses("title") == true, filesByTitle = file?.Uses("title") == true; var taken = occupied.ToList(); var claimed = new HashSet(taken, StringComparer.OrdinalIgnoreCase); // The folders given in this plan so far: Kept never gives one twice (two folders that differ only in case). var given = new HashSet(StringComparer.OrdinalIgnoreCase); bool Unreadable(RenameSubject s) => s.Unreadable || (file is not null && s.Files is null); // A folder that holds a sequence whose sidecar cannot be read cannot take it along. var stuck = subjects.Where(Unreadable).Concat((nested ?? []).Where(n => n.Unreadable)).ToList(); var blockers = new HashSet(); var own = new List(subjects.Count); foreach (var s in subjects) { if (Unreadable(s)) { own.Add(new RenameStep(s.SequenceId, s.Folder, s.Folder, s.Title, s.Title) { Blocked = [new RenameBlocked(RenameBlock.Unreadable, 0)] }); continue; } var context = Context(s); var newTitle = NewTitle(context, s.Title, title); var newFolder = s.Folder; // The archive root itself (a folder adopted in place) cannot move; only its title changes. if (folder is not null && context is not null && s.Folder.Length > 0 && NewFolder(context, newTitle, folder) is { } expanded && !expanded.Equals(s.Folder, StringComparison.Ordinal)) { var inside = stuck.Where(u => IsInside(s.Folder, u.Folder)).Select(u => u.SequenceId).ToList(); if (inside.Count > 0) { blockers.UnionWith(inside); } else { newFolder = Kept(s.Folder, expanded, taken, given, existsExactly) ?? Unique(expanded, claimed, existsOnDisk); claimed.Add(newFolder); given.Add(newFolder); } } var step = new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle); if (file is not null) step = WithFiles(step, s.Files!, file, newTitle); own.Add(step with { NamedByTitle = (folderByTitle && step.MovesFolder) || (filesByTitle && step.FileChanges > 0) }); } var moving = own.Where(s => s.MovesFolder).ToList(); foreach (var step in moving) { // Into a sequence's folder (its own included) or another target: one sequence would end up inside another. var host = taken.Concat(moving.Where(m => m != step).Select(m => m.ToFolder)).FirstOrDefault(f => IsInside(f, step.ToFolder)); if (host is not null) throw new NestedRenameException(step.ToFolder, host); } var steps = new List<(RenameStep Step, int Order)>(); // An unreadable sequence that kept a folder around it in place is listed with why, as an unreadable subject is. var inner = (nested ?? []).Select(n => new RenameStep(n.SequenceId, n.Folder, n.Folder, n.Title, n.Title) { Blocked = n.Unreadable && blockers.Contains(n.SequenceId) ? [new RenameBlocked(RenameBlock.Unreadable, 0)] : [], }); foreach (var step in own.Concat(inner)) { // The nearest folder around it that moves carries it; a sequence that moves elsewhere leaves before its folder does. var carrier = step.MovesFolder ? null : moving.Where(m => IsInside(m.FromFolder, step.FromFolder)).MaxBy(m => m.FromFolder.Length); if (carrier is not null) steps.Add((step with { ToFolder = carrier.ToFolder + step.FromFolder[carrier.FromFolder.Length..], Carried = true }, 1)); else if (step.MovesFolder) steps.Add((step, -moving.Count(m => m != step && IsInside(m.FromFolder, step.FromFolder)))); else if (step.Retitles || step.FileChanges > 0 || step.Blocked.Count > 0) steps.Add((step, 0)); } // Stable: subjects keep their order, sequences inside moving folders move out first, carried ones come last. return new RenamePlan(Guid.CreateVersion7(), archiveId, [.. steps.OrderBy(s => s.Order).Select(s => s.Step)]) { FileTemplate = fileTemplate, FolderTemplate = folderTemplate, TitleTemplate = titleTemplate, Subjects = [.. subjects.Select(s => s.SequenceId)], }; } /// /// The title and the folder the templates give a sequence from its sidecar () as /// gives them, where {title} of the title template is : the title is /// without a title template or when it expands to nothing; the folder is the expansion itself, /// before any " (2)" (), null without a folder template or when it expands to nothing. /// public static (string? Title, string? Folder) Names(SequenceManifest manifest, string? title, string? folderTemplate, string? titleTemplate) { ArgumentNullException.ThrowIfNull(manifest); var context = Context(manifest, title); var newTitle = NewTitle(context, title, titleTemplate is null ? null : PathTemplate.Parse(titleTemplate)); return (newTitle, folderTemplate is null ? null : NewFolder(context, newTitle, PathTemplate.Parse(folderTemplate))); } /// /// Whether is a folder a plan gives for the expansion /// (): that one, or the " (n)" of it that a folder of that name already there made it take. /// public static bool Gives(string expanded, string folder) { ArgumentNullException.ThrowIfNull(expanded); ArgumentNullException.ThrowIfNull(folder); return folder.Equals(expanded, StringComparison.Ordinal) || (Numbered(folder, expanded, StringComparison.Ordinal) is { } n && n >= 2 && folder.Equals(string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})"), StringComparison.Ordinal)); } /// The n of when it is followed by " (n)"; null otherwise. private static int? Numbered(string folder, string expanded, StringComparison comparison) => folder.Length > expanded.Length + 3 && folder.StartsWith(expanded + " (", comparison) && folder[^1] == ')' && int.TryParse(folder.AsSpan(expanded.Length + 2, folder.Length - expanded.Length - 3), NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? n : null; private static string? NewTitle(NamingContext? context, string? title, PathTemplate? template) => template is null || context is null ? title : Blank(template.ExpandText(context)) ?? title; private static string? NewFolder(NamingContext context, string? newTitle, PathTemplate template) => Blank(template.ExpandFolder(context with { Title = newTitle })); /// /// What the folder and title templates of a subject see: its first frame in its sidecar, as an upload filed it and as /// Reorganize names its files (a sidecar without frames: when the sequence was made); without the sidecar, the index /// row's capture time, camera and lens. Null when no time is known: never today's date, which would move the folder /// again on another day. /// private static NamingContext? Context(RenameSubject s) { if (s.Files?.Manifest is { } manifest) return Context(manifest, s.Title); if (s.FirstCapture is not { } first) return null; return new NamingContext { CapturedAt = first, SessionStart = first, CameraMake = s.CameraMake, CameraModel = s.CameraModel, Lens = s.Lens, Title = s.Title, }; } /// What the folder and title templates see in a sidecar: its first frame (). private static NamingContext Context(SequenceManifest manifest, string? title) { if (manifest.Frames.Count > 0) return FrameNaming.Context(manifest.Frames[0], manifest, title); var start = FrameNaming.SessionStart(manifest); return new NamingContext { CapturedAt = start, SessionStart = start, CameraMake = manifest.Camera?.Make, CameraModel = manifest.Camera?.Model, Lens = manifest.Lens, Title = title, }; } /// The step with the file renames of its sequence (). private static RenameStep WithFiles(RenameStep step, SequenceFiles files, PathTemplate template, string? title) { var plan = FileRenames.Plan(files.Manifest, title, template, files.Present); return step with { FramesVersion = plan.Frames > 0 ? files.Manifest.Versions.Frames : 0, FileChanges = plan.Frames, FileSamples = plan.Samples, FileDigest = plan.Frames > 0 ? plan.Digest() : null, Blocked = plan.Blocked, }; } /// /// Whether lies inside (archive-relative, forward slashes); the /// archive root, a sequence only when a folder was adopted in place, counts as containing nothing. /// public static bool IsInside(string folder, string path) => folder.Length > 0 && path.Length > folder.Length + 1 && path[folder.Length] == '/' && path.StartsWith(folder, StringComparison.OrdinalIgnoreCase); /// /// Moves the folder of a step; idempotent so a resumed plan can repeat it: an already moved folder is accepted, /// a case-only change goes through a temporary name (case-insensitive file systems). /// /// The target is occupied by something else (for a case-only change, a folder of its own /// on a case-sensitive file system, which the plan and the apply refuse first), or neither folder exists. public static void MoveFolder(ArchivePaths archive, RenameStep step) { if (!step.MovesFolder) return; var from = archive.FromRelative(step.FromFolder); var to = archive.FromRelative(step.ToFolder); var caseOnly = step.FromFolder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase); if (Directory.Exists(to) && (!caseOnly || ExistsExactly(archive, step.ToFolder))) { // Both names there: the target is another folder (for a case-only change, on a case-sensitive file system). if (Directory.Exists(from) && (!caseOnly || ExistsExactly(archive, step.FromFolder))) throw new IOException($"Rename target {step.ToFolder} already exists."); return; } if (!Directory.Exists(from)) throw new DirectoryNotFoundException($"Sequence folder {step.FromFolder} is missing."); Directory.CreateDirectory(Path.GetDirectoryName(to)!); if (caseOnly) { var temp = from + ".rename-" + Guid.NewGuid().ToString("N")[..8]; Directory.Move(from, temp); Directory.Move(temp, to); } else { Directory.Move(from, to); } } /// /// Whether the folder (archive-relative, forward slashes) is on disk with exactly that name at /// every level. On a case-insensitive file system a folder whose name differs in case only does not count, so a change /// of case only finds its own folder under its old name alone; on a case-sensitive one this is any folder of that name. /// public static bool ExistsExactly(ArchivePaths archive, string folder) { ArgumentNullException.ThrowIfNull(archive); ArgumentNullException.ThrowIfNull(folder); var path = archive.Root; var options = new EnumerationOptions { MatchType = MatchType.Simple, AttributesToSkip = 0, IgnoreInaccessible = true }; foreach (var name in folder.Split('/', StringSplitOptions.RemoveEmptyEntries)) { try { // The name as a pattern finds it whatever its case on Windows; only the exact one counts. if (!Directory.EnumerateDirectories(path, name, options).Any(d => Path.GetFileName(d).Equals(name, StringComparison.Ordinal))) return false; } catch (DirectoryNotFoundException) { return false; } path = Path.Combine(path, name); } return Directory.Exists(path); } private static string? Blank(string value) => string.IsNullOrWhiteSpace(value) ? null : value; /// /// The folder a sequence keeps (in the template's case) when it already is , or the /// " (n)" of it that filing or an earlier Reorganize gave it beside another sequence of that name; null when it is /// neither, when another folder holds that name exactly (a sequence's, or one on disk beside the sequence's own folder, /// on a case-sensitive file system: finds both names), which the change of case could /// never move onto, or when this plan already gave it to another sequence (, whatever its case: /// trip (2) and TRIP (2) both keep Trip (2) otherwise). Without it a sequence at /// 2026-09-28 (2) would be planned to (3), its own folder being taken, and back to (2) by the next /// Reorganize. /// private static string? Kept(string current, string expanded, IReadOnlyList occupied, IReadOnlySet given, Func existsExactly) { string? same = null; if (current.Equals(expanded, StringComparison.OrdinalIgnoreCase)) same = expanded; else if (Numbered(current, expanded, StringComparison.OrdinalIgnoreCase) is { } n && n >= 2) same = string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})"); // "(02)" is not a number Unique gives: that folder moves to a name of its own. if (same is null || !same.Equals(current, StringComparison.OrdinalIgnoreCase) || given.Contains(same)) return null; if (same.Equals(current, StringComparison.Ordinal)) return same; // The new name on disk is another folder only while the sequence's own is there under the index's name too, as // MoveFolder throws: on a case-insensitive file system the disk may spell the sequence's own folder as the template // does (renamed in Explorer, or an outer level a change of case left as it was), and that folder is no other. return occupied.Any(o => o.Equals(same, StringComparison.Ordinal)) || (existsExactly(same) && existsExactly(current)) ? null : same; } private static string Unique(string folder, HashSet claimed, Func existsOnDisk) { var candidate = folder; for (var n = 2; claimed.Contains(candidate) || existsOnDisk(candidate); n++) candidate = string.Create(CultureInfo.InvariantCulture, $"{folder} ({n})"); return candidate; } }