Skip to main content

C# extension method that ensures the given file name will return a unique file name, using the format Filename - Copy, or Filename - Copy (n) where n > 1.

// ----------------------------------------------------------------------------
// Ensure Unique File Name
//
// Ensures given file name will return a unique file name, using the format
// Filename - Copy, or Filename - Copy (n) where n > 1.
// ----------------------------------------------------------------------------

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 Usage:
// ----------------------------------------------------------------------------

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