2015-06-22 131 views
0

嘗試在C#中運行刪除應用程序。如果目錄中有超過10個文件,請刪除最舊的文件,然後再次迭代。然後繼續,直到只剩下10個文件。我在foreach循環有幫助,有一天,發現在Trying to delete files older than X number of days on insert in .NET MVC指數超出範圍。必須是非負值或小於收集的大小

現在試圖做一個for循環。在運行時,我得到「必須是非負值且小於集合的大小」,但是「索引」小於集合的集合,其當前爲「16」。

static void Main() 
{ 
    DirectoryInfo dir = new DirectoryInfo(@"N:/Bulletins/October"); 
    List<FileInfo> filePaths = dir.GetFiles().OrderBy(p => p.CreationTime).ToList(); 
    for (int index = filePaths.Count(); filePaths.Count() > 9; index--) 
    { 
     Console.WriteLine(index); 
     filePaths[index].Delete(); 
     filePaths.RemoveAt(index); 
    } 
} 

任何想法?

感謝

編輯:

我應該提到的「foreach」循環是基於它是否是年齡超過10天,但我們意識到,兩個星期的假期將徹底清除整個批次,其中,因爲我們希望保持現有的10個文件

+0

是「filePaths.Count()> 9;」 for循環的部分與index-1不同? –

+0

是的,我忽略了@South –

回答

2

看起來你在你的循環狀況有一個錯字:

for (int index = filePaths.Count(); filePaths.Count() > 9; index--) 

它應該是

for (int index = filePaths.Count() - 1; index > 9; index--) 

還要注意,for循環的第一次迭代你想訪問filePaths[filePaths.Count()]這顯然是不存在的,因爲在C#中的數組是從零開始的。所以它應該是filePaths.Count() - 1作爲起始索引。

+0

@SouthWilts看到更新的答案 –

+0

這很好用:)。謝謝! –

相關問題