嘗試在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個文件
是「filePaths.Count()> 9;」 for循環的部分與index-1不同? –
是的,我忽略了@South –