February 13, 2023

File Renamer

Rename a file when you have a path. This was written as a LinqPad script

void Main()
{
    Console.WriteLine(FileRenamer. CalcNewFilePath (@"c:/some/Directory/File.pdf"));
    Console.WriteLine(FileRenamer. CalcNewFilePath (@"File.pdf"));
    Console.WriteLine(FileRenamer. CalcNewFilePath (@"C:File.pdf"));
    Console.WriteLine(FileRenamer. CalcNewFilePath (@"/some/Directory/File.pdf"));
    Console.WriteLine(FileRenamer. CalcNewFilePath (@"/some\Directory/File.pdf"));
    Console.WriteLine(FileRenamer. CalcNewFilePath (@"e:\zdump\some\Directory\File.pdf"));
}

public static class FileRenamer
{
    const string Suffix = @"-xx";

    /// <summary>
    /// Calculate the file path of the file, changing the file name
    /// in the process
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static string CalcNewFilePath(string filePath)
    {
        if (string.IsNullOrWhiteSpace(filePath))
            return "";
        var ext = Path.GetExtension(filePath);
        var bareFileName = Path.GetFileNameWithoutExtension(filePath);
       
        var path = GetFilePathStem(filePath);

    var fileNameTemplate = $"{path}{bareFileName}{Suffix}{ext}";
    return fileNameTemplate;
}

/// <summary>
/// Get the stem of the file path, everything before the actual filename.
/// It assumes that the last part of the path after the 
/// final Directory Seperator character is the filename
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string GetFilePathStem(string filePath)
{
    var path = "";
    var endofPath1 = filePath.LastIndexOf(Path.DirectorySeparatorChar);
    var endofPath2 = Path.AltDirectorySeparatorChar != 
      Path.DirectorySeparatorChar ? filePath.LastIndexOf(Path.AltDirectorySeparatorChar) : -1;
    var endofPath = Math.Max(endofPath1, endofPath2);
    if (endofPath > 0)
    {
        path = filePath.Substring(0, endofPath + 1);
    }
    else // When the root does not use a directory separator char eg. "c:filename.pdf"
    {
        var root = Path.GetPathRoot(filePath);
        path = root;
    }
    return path;
}