Q: Not able to remove file from a Sharepoint FileCollection list I am working on a function that will check a users file collection in SharePoint for any file that is more than a minute old (this will be changed, and only using it for testing).  However, when the condition is true it goes into removing the file which is older than a minute, but I get the following exception message.
System.InvalidOperationException
The collection was modified. Enumeration operation  may not execute. 
  private static void check_for_deletion(PHT.OneDrive.Helpers.OneDriveHelper oneDrive, string user)
    {
        FileCollection files = oneDrive.GetOneDriveFilesByFolderName(user);

        foreach (var file in files)
        {

            DateTime creationDate = file.TimeCreated.ToLocalTime();
            DateTime currentTime = DateTime.Now;
            TimeSpan elapsedTime = currentTime.Subtract(creationDate);
            int fileAge = elapsedTime.Minutes;
            int maxTime = 1;


            if (fileAge > maxTime)
            {
                file.DeleteObject();
            }
        }
     }


A: You should be able to complete it within the same file collection, just loop through it backwards:
for (int fileNum = files.Count-1; fileNum >= 0; fileNum--)
    {
        //Assign file within the loop
        var file = files[fileNum];

        DateTime creationDate = file.TimeCreated.ToLocalTime();
        DateTime currentTime = DateTime.Now;
        TimeSpan elapsedTime = currentTime.Subtract(creationDate);
        int fileAge = elapsedTime.Minutes;
        int maxTime = 1;


        if (fileAge > maxTime)
        {
            file.DeleteObject();
        }
    }


A: Your modifying the FileCollection files inside your foreach loop.
Once you complete your search create a new FileCollection and copy the contents of files to this and then iterate over the new one.
