c# - C#创建文件夹时添加数字后缀

标签 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);
    }

最佳答案

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

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/

相关文章:

php - 测试一个目录是否是另一个文件夹的子目录

python - 计算 DataFrame 中列中的单词

c# - 运行时显示错误的字体

c# - 如何从开罗保存 jpg

c# - 如何使 C# Powershell Invoke 成员线程安全

c - 显示访问文件夹的进程

c# - 如何在 WPF 中获取 "Selected MenuItem"

c - 验证 _tmkdir 是否成功

java - 介意帮助第一次遇到减速带的新人吗?

javascript - 为什么我的轮播中的计数器在达到 0 索引和最大索引后返回负值?