Automatically rename a file if it already exists in Windows way

This will check for the existence of files with tempFileName and increment the number by one until it finds a name that does not exist in the directory.

int count = 1;

string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);
string extension = Path.GetExtension(fullPath);
string path = Path.GetDirectoryName(fullPath);
string newFullPath = fullPath;

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

Leave a Comment