Trying to run a delete application in C#. If there is more than 10 files in a directory, delete the oldest file, and iterate again. Then continue until there is only 10 files remaining. I had help with this in a foreach loop the other day, found at Trying to delete files older than X number of days on insert in .NET MVC
Now trying to do this in a for loop. When running, I get "Must be non-negative and less than size of the collection" but "Index" is less than the collection, which currently stands at "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);
}
}
Any ideas?
Thanks
Edit:
I should mention, the "foreach" loop was to be based on whether or not it was older than 10 days, but we realised that a two week holiday will completely clear the entire lot, where as we want to keep the previous 10 files