2012-01-29 29 views
4

我想要处理,如果我想创建的文件夹已经存在..添加数字到文件夹名称..喜欢Windows资源管理器..例如(新建文件夹,新建文件夹1,新建文件夹2 ..) 我该怎么做递归 我知道这段代码是错误的。 我该如何修复或者更改下面的代码来解决问题?在C#中创建文件夹时添加数字后缀

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

回答

5

为此,您不需要递归,而是应该着眼于迭代求解

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)); 
} 
+0

非常感谢:) ..毫米我有一个可爱的小问题..我用树状作出了文件浏览器..现在我想用列表视图做..如何让ParentNode ..在列表视图..我的意思是目前的文件夹..有没有在listviewitem选项或我必须保存在字符串中的当前路径? – 2012-01-29 17:22:54

+0

'ListViewItem'对象具有'Tag'属性,您可以在其中存储任意数据。你可以把路径放在这里。 – JaredPar 2012-01-29 17:25:20

+0

很酷..出于某种原因,我不知道为什么..当我给路径@“D:”..它创建磁盘C:..为什么? – 2012-01-29 17:30:27

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

做的simpliest方法是:

 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

您可以使用此功能DirectoryInfo的扩展:

public static class DirectoryInfoExtender 
{ 
    public static void CreateDirectory(this DirectoryInfo instance) 
    { 
     if (instance.Parent != null) 
     { 
      CreateDirectory(instance.Parent); 
     } 
     if (!instance.Exists) 
     { 
      instance.Create(); 
     } 
    } 
} 
相关问题