如果我想创建的文件夹已经存在,我正在尝试处理..向文件夹名称添加一个数字..就像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);
}
最佳答案
为此,您不需要递归,而是应该寻求迭代解决方案:
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));
}
关于c# - C#创建文件夹时添加数字后缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9054952/