Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
like image 600
Murhaf Sousli Avatar asked Dec 28 '22 07:12

Murhaf Sousli


2 Answers

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));
}
like image 72
JaredPar Avatar answered Jan 04 '23 09:01

JaredPar


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

credit for @JaredPar

like image 24
Murhaf Sousli Avatar answered Jan 04 '23 08:01

Murhaf Sousli