System.InvalidOperationException: Collection was modified; enumeration operation may not execute

Hi,I am trying to delete sheets in a work book if the sheet name is not equal to certain value but I am getting the error as "System.InvalidOperationException: Collection was modified; enumeration operation may not execute.". Below is my code, please check and let me know what is wrong.

Workbook

wb = new Workbook();

wb.Open(FileName);

Worksheet ws = wb.Worksheets[VersionName];

Workbook

wb = new Workbook();

wb.Open(FileName);

Worksheet ws = wb.Worksheets[VersionName];

foreach

(Worksheet sheet in wb.Worksheets)

{

if (!sheet.Name.Equals(VersionName, StringComparison.InvariantCultureIgnoreCase))

{

wb.Worksheets.RemoveAt(sheet.Name);

}

}

foreach

(Worksheet sheet in wb.Worksheets)

{

if (!sheet.Name.Equals(VersionName, StringComparison.InvariantCultureIgnoreCase))

{

wb.Worksheets.RemoveAt(sheet.Name);

}

}

Thanks,

Jyotshna

Hi Jyotshna,

Thank you for considering Aspose products.

Your presented problem is due to the reason that you are iterating over a collection and deleting a few entries from it, that modifies the collection therefore in next iteration the code throws the said error. Please modify the code as follow to delete the worksheet from a collection as per your exact requirements.
C#


WorksheetCollection sheets = book.Worksheets;
for (int index = 0; index < sheets.Count; index++ )
{
Worksheet sheet = sheets[index];
if (sheet.Name.Equals(name))
{
book.Worksheets.RemoveAt(index);
}
}