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

时间:2012-01-29 17:04:30

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

4 个答案:

答案 0 :(得分: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));
}

答案 1 :(得分: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的信用

答案 2 :(得分: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();
          }
        }

答案 3 :(得分: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();
        }
    }
}