EnsureFileNameIsUnique

public static string EnsureFileNameIsUnique(this string intendedName)
{
    if (!File.Exists(intendedName)) return intendedName;

    FileInfo file = new FileInfo(intendedName);
    string extension = file.Extension;
    string basePath = intendedName.Substring(0, intendedName.Length - extension.Length);

    int counter = 1;

    string newPath = "";

    do
    {
        newPath = string.Format("{0} - Copy{1}{2}", basePath, counter == 1 ? "" : string.Format(" ({0})", counter), extension);

        counter += 1;
    }
    while (File.Exists(newPath));

    return newPath;
}
Example:
//Move file to new location
string fileToMove = @"C:/myfiletomove.txt";
string newLocation = Path.Combine(directoryName, fileName);

//Ensure if File Exists, then File.Move will use a unique name
//In the Windows "FileName - Copy [(#)]" format
File.Move(fileToMove, newLocation.EnsureFileNameIsUnique());

Description

Ensures given file name will return a unique file name, using the format Filename - Copy, or Filename - Copy (n) where n > 1

Details

Double click on the code to select all.

 

;