using System; using System.Collections.Generic; using System.IO; using System.Text; namespace StarterNG.Application.Abstractions; public interface IFileSystem { /// Whether a name finds its file whatever the case of its letters, as on Windows and macOS. bool IgnoresCase { get; } bool FileExists(string path); bool DirectoryExists(string path); string ReadAllText(string path); string ReadAllText(string path, Encoding encoding); string[] ReadAllLines(string path); byte[] ReadAllBytes(string path); Stream OpenRead(string path); void WriteAllText(string path, string contents); void WriteAllText(string path, string contents, Encoding encoding); /// /// Writes the file whole or not at all: a crash or a full disk half way leaves /// what stood there, not the start of what was on its way. A link stays a link, /// its file gets the contents; a file keeps its mode. /// void WriteAllBytesAtomic(string path, byte[] bytes); /// As UTF-8 without a mark, by . void WriteAllTextAtomic(string path, string contents); void WriteAllLines(string path, IEnumerable lines); void WriteAllBytes(string path, byte[] bytes); void CreateDirectory(string path); void DeleteFile(string path); void CopyFile(string sourcePath, string destinationPath, bool overwrite); IReadOnlyList GetFiles(string path, string searchPattern = "*"); IReadOnlyList GetDirectories(string path); IReadOnlyList GetFilesRecursive(string path, string searchPattern); DateTime GetLastWriteTimeUtc(string path); long GetFileSize(string path); /// A file's time and size in one look; null when there is no file. (DateTime LastWriteUtc, long Size)? LastWriteAndSize(string path); bool IsExecutable(string path); /// Where the symbolic link at points, or null for anything else. string? LinkTarget(string path); /// Makes a symbolic link to the directory . void CreateDirectoryLink(string path, string target); void MoveDirectory(string sourcePath, string destinationPath); } public static class FileSystemExtensions { /// /// Copies a file that could not be read beside itself, before something replaces /// it: it may hold what was not read. Throws when it cannot; then it must stay. /// public static void KeepAside(this IFileSystem files, string path, IDiagnosticsLog log) { if (!files.FileExists(path)) return; string aside = path + ".unreadable"; for (int n = 2; files.FileExists(aside); n++) aside = $"{path}.unreadable-{n}"; files.CopyFile(path, aside, overwrite: false); log.Log($"{path} could not be read; a copy is kept as {aside}"); } }