Move FileInfo and automatically rename it

/// <summary>
/// Move current instance and rename current instance when needed
/// </summary>
/// <param name="fileInfo">Current instance</param>
/// <param name="destFileName">The Path to move current instance to, which can specify a different file name</param>
/// <param name="renameWhenExists">Bool to specify if current instance should be renamed when exists</param>
public static void MoveTo(this FileInfo fileInfo, string destFileName, bool renameWhenExists = false)
{
    string newFullPath = string.Empty;

    if(renameWhenExists)
    {
        int count = 1;

        string fileNameOnly = Path.GetFileNameWithoutExtension(fileInfo.FullName);
        string extension = Path.GetExtension(fileInfo.FullName);
        newFullPath = Path.Combine(destFileName, fileInfo.Name);

        while (File.Exists(newFullPath))
        {
            string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
            newFullPath = Path.Combine(destFileName, tempFileName + extension);
        }
    }

    fileInfo.MoveTo(renameWhenExists ? newFullPath : destFileName);
}
Example:
FileInfo fileInfo = new FileInfo(@"c:\test.txt");
File.Create(fileInfo.FullName).Dispose();
fileInfo.MoveTo(@"d:\", true);

Description

Moves a FileInfo instance to a specified path and rename it when already existing.

Details

Double click on the code to select all.

 

;