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);
}
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));
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With