Create folder

Dani_S 4,501 Reputation points
2024-08-05T07:31:53.65+00:00

Hi,

I want to create new folder, but it can be exist.

How I handel this case of renaming?

Thanks,

Developer technologies .NET .NET MAUI
Developer technologies .NET Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-08-05T09:25:43.6866667+00:00

    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.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.