首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C#中创建文件夹时添加数字后缀

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

Stack Overflow用户
提问于 2012-01-30 01:04:30
回答 4查看 4.8K关注 0票数 4

如果要创建的文件夹已经存在,我正在尝试处理。要在文件夹名称中添加数字,请执行以下操作。就像windows资源管理器..例如(新建文件夹、新建文件夹1、新建文件夹2 ..)我怎么才能递归呢?我知道这段代码是错误的。我如何修复或者修改下面的代码来解决这个问题?

代码语言:javascript
复制
    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);
    }
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-01-30 01:09:39

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

代码语言:javascript
复制
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));
}
票数 7
EN

Stack Overflow用户

发布于 2012-01-31 22:11:25

代码语言:javascript
复制
    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
EN

Stack Overflow用户

发布于 2012-06-27 01:39:31

最简单的方法是:

代码语言:javascript
复制
        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();
          }
        }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9054952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档