2013-03-20 109 views
0

我可以在普通表單應用程序中執行此任務,但我是使用WPF應用程序的全新功能。C# - 如何遞歸搜索WPF應用程序中的目錄?

我想在TextBox中輸入一個目錄路徑,然後單擊一個Button,它將驗證並遞歸搜索該路徑,並將所有文件顯示在ListBox中。

我已經看過this文章,但我不完全理解它,因爲我再次對此非常陌生。

任何幫助,將不勝感激。

+0

你從你鏈接的鏈接中知道些什麼?如果我們排除try catch,則有5行。 – coolmine 2013-03-20 02:10:35

+2

僅供參考,遞歸搜索目錄與WPF沒有任何關係。這是C#的基礎。 – joce 2013-03-20 02:29:56

回答

6

試試這個。

DirectoryInfo dir = new DirectoryInfo("your path"); 
dir.GetFiles("*.*", SearchOption.AllDirectories); 
+5

使用'EnumerateFiles'提高效率:http://stackoverflow.com/questions/5669617/what-is-the-difference-between-directory-enumeratefiles-vs-directory-getfiles – 2013-03-20 02:15:45

1

或者這個;

void DirSearch(string sDir) 
{ 
    try 
    { 
     foreach (string d in Directory.GetDirectories(sDir)) 
     { 
     foreach (string f in Directory.GetFiles(d, txtFile.Text)) 
     { 
      lstFilesFound.Items.Add(f); 
     } 
     DirSearch(d); 
     } 
    } 
    catch (System.Exception excpt) 
    { 
     Console.WriteLine(excpt.Message); 
    } 
} 
+0

所以我把這個放進去,但是我的代碼是什麼放在搜索按鈕事件處理程序? – user2189007 2013-03-20 03:20:14

+1

+1。 @ user2189007 - 您提出了關於進行遞歸搜索的問題。如果你真的需要別的東西(基於這個評論似乎是這種情況) - 請詢問你有問題的確切任務。 – 2013-03-20 03:33:52