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

4
我正在尝试处理如果我想要创建的文件夹已经存在的情况...可以在文件夹名称后面添加一个数字,就像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);
    }
4个回答

7
为此,您不需要递归,而应该寻找迭代解决方案:
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));
}

ListViewItem对象有一个Tag属性,您可以在其中存储任意数据。您可以将路径放在这里。 - JaredPar
很酷啊..出于某些我不知道的原因..当我给出路径@"d:"时..它在C盘上创建了..为什么呢?? - Murhaf Sousli
@MurHafSoz 这是Windows的一个非常烦人的遗留问题。如果您不至少指定到反斜杠,它将给出您意料之外的行为。因此,d:\d:是不同的。 - JaredPar
实际上,当我使用 console.writeline(Path.Combine(path, current)) 时,它只显示 \new folder ..,所以它可能正在获取当前目录,即 c:.. 因此 Path.Combine 函数有些问题,请检查一下。 - Murhaf Sousli
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/7143/discussion-between-mur-haf-soz-and-jaredpar - Murhaf Sousli
显示剩余4条评论

1
    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);
    }

感谢 @JaredPar 的贡献


1
您可以使用此DirectoryInfo扩展程序:
public static class DirectoryInfoExtender
{
    public static void CreateDirectory(this DirectoryInfo instance)
    {
        if (instance.Parent != null)
        {
            CreateDirectory(instance.Parent);
        }
        if (!instance.Exists)
        {
            instance.Create();
        }
    }
}

1

最简单的方法是:

        public static void ebfFolderCreate(Object s1)
        {
          DirectoryInfo di = new DirectoryInfo(s1.ToString());
          if (di.Parent != null && !di.Exists)
          {
              ebfFolderCreate(di.Parent.FullName);
          }

          if (!di.Exists)
          {
              di.Create();
              di.Refresh();
          }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接