Automatically rename a file if it already exists in Windows way

Solution 1:

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

Solution 2:

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

Solution 3:

The other examples don't take into account the filename / extension.

Here you go:

    public static string GetUniqueFilename(string fullPath)
    {
        if (!Path.IsPathRooted(fullPath))
            fullPath = Path.GetFullPath(fullPath);
        if (File.Exists(fullPath))
        {
            String filename = Path.GetFileName(fullPath);
            String path = fullPath.Substring(0, fullPath.Length - filename.Length);
            String filenameWOExt = Path.GetFileNameWithoutExtension(fullPath);
            String ext = Path.GetExtension(fullPath);
            int n = 1;
            do
            {
                fullPath = Path.Combine(path, String.Format("{0} ({1}){2}", filenameWOExt, (n++), ext));
            }
            while (File.Exists(fullPath));
        }
        return fullPath;
    }