2016-11-11 76 views
0

我使用以下代碼來嘗試計算MyDocuments中的所有目錄和文件。在MyDocuments中無法獲得子目錄和文件的任何文件數C#

該代碼可以使用所有其他特殊文件夾(收藏夾,桌面,照片等)

但是,當我試圖讓的「我的文檔」的計數,它失敗。當我得到的計數在其他目錄其中工程 -

  /*DOCUMENTS*/    
      documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
      fileCount = Directory.GetFiles(documentsFolder, "*.*", SearchOption.AllDirectories).Length; //THIS IS WHERE IT FAILS - DOES NOT GET PAST HERE 
      MessageBox.Show(fileCount.ToString()); //THIS NEVER SHOWS 

,當我試圖讓fileCount它失敗。

該目錄是在我的電腦上尺寸相當大 - 也許我需要「等待」,而它計算?

我不明白爲什麼它不工作,但所有其他工作正常,沒有問題使用基本相同的代碼。

+0

你能給我錯誤的訪問? –

+0

很奇怪,因爲它不揭開序幕的錯誤 - 它只是結束處理,並移動到下一個代碼位。 – Hanny

+0

我覺得你有機會在這方面的一些子文件夾否認......我想你的代碼段,這就是失敗。代碼返回一個異常。試試看。 – Turrican

回答

0

我能想到的唯一的辦法是排除的文件夾沒有從文件數

int fileCount = 0; 
var pathToSearch = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 

//retrieve files 
fileCount += Directory.GetFiles(pathToSearch, "*.*", SearchOption.TopDirectoryOnly).Length; 

//retrieve folders 
foreach (var subFolder in Directory.GetDirectories(pathToSearch, "*.*", SearchOption.TopDirectoryOnly)) 
{ 
    try { Array.ForEach(Directory.GetFiles(subFolder, "*.*", SearchOption.AllDirectories), f => fileCount++); } 
    catch { }   
} 

MessageBox.Show($"{fileCount}"); 
相關問題