ExtensionMethod.NET Home of 829 C#, Visual Basic, F# and Javascript extension methods

Move FileInfo and automatically rename it

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


/// <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;

        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);


FileInfo fileInfo = new FileInfo(@"c:\test.txt");
fileInfo.MoveTo(@"d:\", true);

Author: Peter Rietveld

Submitted on: 22 apr 2013

Language: C#

Type: FileInfo

Views: 7127