2012-01-29 110 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(); 
     } 
    } 
} 
相關問題