0

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

Community
  • 1
  • 1
South Wilts
  • 121
  • 1
  • 14

1 Answers1

2

It looks like you have a typo in your loop condition:

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

It should be

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

Also note that for the first iteration of loop you're trying to access filePaths[filePaths.Count()] which is obviously not exists since arrays in C# are zero based. So it should be filePaths.Count() - 1 as starting index.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71