Hi @Dani_S , Welcome to Microsoft Q&A,
To create a new folder in C# while handling the case where the folder might already exist and you want to rename it, you can use the following method. If it does exist, append a number to the folder name until a unique name is found.
using System;
using System.IO;
public class Program
{
public static void Main()
{
string folderPath = @"C:\Example\NewFolder";
string newFolderPath = CreateUniqueFolder(folderPath);
Console.WriteLine($"Created folder: {newFolderPath}");
}
public static string CreateUniqueFolder(string folderPath)
{
string uniqueFolderPath = folderPath;
int counter = 1;
while (Directory.Exists(uniqueFolderPath))
{
uniqueFolderPath = $"{folderPath}_{counter}";
counter++;
}
Directory.CreateDirectory(uniqueFolderPath);
return uniqueFolderPath;
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.