2013-10-03 51 views
-1

如何從子目錄獲取文件,以及使用該代碼只獲取目錄下的文件所做的工作列出:Directory.GetFiles如何訪問子目錄?

DirectoryInfo selDir = new DirectoryInfo(folderBrowserDialog1.SelectedPath); 
    Directory.CreateDirectory(folderBrowserDialog1.SelectedPath + "\\Output"); 

foreach (FileInfo d in selDir.GetFiles()) 
    { 
     //my code 
    } 
+2

您必須盲目瞭解這段代碼,您剛創建的目錄不會有任何文件。 –

+0

哦,我真的很抱歉,代碼是不完整的,讓我編輯that.Done。 – Omarrrio

+1

-1:如果您尚未找到如何包含子目錄,則甚至無法閱讀已調用方法的文檔:http://msdn.microsoft.com/en-us/library/system。 io.directoryinfo.getfiles.aspx –

回答

4
var allFiles = selDir.GetFiles("*.*", SearchOption.AllDirectories); 
+0

謝謝你,先生,作品像魅力。 – Omarrrio

1
DirectoryInfo selDir = new DirectoryInfo(folderBrowserDialog1.SelectedPath); 
Directory.CreateDirectory(folderBrowserDialog1.SelectedPath + "\\Output"); 

string[] files = Directory.GetFiles(selDir.FullName, "*.*", SearchOption.AllDirectories); 

foreach (string file in files) 
{ 
    // your code 
} 
2

你有你想要的文件夾的DirectoryInfo的,所以環在所有的目錄中,然後你可以得到每個文件。

DirectoryInfo selDir = new DirectoryInfo(folderBrowserDialog1.SelectedPath); 
Directory.CreateDirectory(Path.Combine(folderBrowserDialog1.SelectedPath, "Output")); 

foreach (string dir in System.IO.Directory.GetDirectories(selDir.FullName, "*.*", System.IO.SearchOption.AllDirectories)) 
{ 
    foreach (string file in Directory.GetFiles(dir)) 
    { 
     //my code 
    } 
} 
+0

不會工作,因爲dir是一個「GetDirectories」而不是「GetFiles」,但是謝謝 – Omarrrio

2

我通常做一個經常性的方法來做到這一點。例如:

private void getFiles(string directory) 
    { 
     string[] files = Directory.GetFiles(directory); 
     string[] directories = Directory.GetDirectories(directory); 

     foreach (string file in files) 
     { 
      // Code here. 
     } 

     foreach (string subDirectory in directories) 
     { 
      // Call the same method on each directory. 
      getFiles(subDirectory); 
     } 
    } 
+0

爲什麼不在調用'GetFiles'時只使用'SearchOption.AllDirectories'? –