Automatically rename a file if it already exists in Windows way

With this code if file name is "Test (3).txt" then it will become "Test (4).txt".

public static string GetUniqueFilePath(string filePath)
{
    if (File.Exists(filePath))
    {
        string folderPath = Path.GetDirectoryName(filePath);
        string fileName = Path.GetFileNameWithoutExtension(filePath);
        string fileExtension = Path.GetExtension(filePath);
        int number = 1;

        Match regex = Regex.Match(fileName, @"^(.+) \((\d+)\)$");

        if (regex.Success)
        {
            fileName = regex.Groups[1].Value;
            number = int.Parse(regex.Groups[2].Value);
        }

        do
        {
            number++;
            string newFileName = $"{fileName} ({number}){fileExtension}";
            filePath = Path.Combine(folderPath, newFileName);
        }
        while (File.Exists(filePath));
    }

    return filePath;
}

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

Tags:

C#

.Net