在C#中创建文件夹时添加数字后缀

Mur*_*sli 4 c# directory counter

我正在尝试处理如果我想要创建的文件夹已经存在..添加一个数字到文件夹名称..像Windows资源管理器..例如(新文件夹,新文件夹1,新文件夹2 ..)我怎么能以递归方式做到我知道这段代码是错误的.我该如何修复或改变下面的代码来解决问题?

    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);
    }
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 6

为此,您不需要递归,而应该寻求迭代解决方案

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