Search code examples
c#directorycounter

Adding a number suffix when creating folder in C#


I'm trying to handle if the folder i want to create is already exist .. to add a number to folder name .. like windows explorer .. e.g(New Folder , New Folder 1 , New Folder 2 ..) how can i do it recursively i know this code is wrong. how can i fix or maybe change the code below to solve the problem ?

    int i = 0;
    private void NewFolder(string path)
    {
        string name = "\\New Folder";
        if (Directory.Exists(path + name))
        {
            i++;
            NewFolder(path + name +" "+ i);
        }
        Directory.CreateDirectory(path + name);
    }

Solution

  • For this, you don't need recursion, but instead should look to an iterative solution:

    private void NewFolder(string path) {
        string name = @"\New Folder";
        string current = name;
        int i = 1;
        while (Directory.Exists(Path.Combine(path, current))) {
            i++;
            current = String.Format("{0}{1}", name, i);
        }
        Directory.CreateDirectory(Path.Combine(path, current));
    }