Adjacent Bookmarks


#1

Hello

I am replacing the text inside bookmarks. Everything works fine when the bookmarks have some characters between them. As soon as two bookmarks adjacent (like [bookmark1][bookmark2] ) then the following Exception occurs:

An unhandled exception of type ‘System.InvalidOperationException’ occurred in mscorlib.dllAdditional information: Collection was modified; enumeration operation may not execute.

I suspect that this happen because the two bookmarks “melt together” as soon as I replace the text of one bookmark.

I would prefer to leave the two bookmarks intact, so that I could call my routine again and again, thus refreshing the document data.

How can I meet this requirement ?


// My code:
Aspose.Word.Document doc = new Aspose.Word.Document (@“c:\test.doc”);
foreach (Aspose.Word.Section section in doc.Sections)
{
foreach (Aspose.Word.Bookmark bm in section.Range.Bookmarks)
{
bm.Text = “dummy data”;
}
}

doc.Save (@“c:\test.doc”);


#2

You need to stop using foreach when enumerating over bookmarks in this case, try using for loop and if that does not help, try using for loop that enumerates from end to beginning of the document.

Let me know if that does not help.


#3

Sorry, but this did not help. I think it is obvious that the Enumerator throws an exception because the Collection of bookmarks changes while the enumerator is still enumerating the List of bookmarks. Replacing the text in a bookmark causes it to merge with the adjacent bookmark, if there is no text between the two bookmarks.

With Word, we had similar problems, which could be resolved with the following article:

http://word.mvps.org/FAQs/MacrosVBA/InsertingTextAtBookmark.htm

I will send you a small application and a word document which demonstrates the problem.

Kind Regards
Matthias


#4

Fixed in Aspose.Word 2.1.14, for more info see http://aspose.com/blogs/Roman.Korchagin/archive/2005/02/25/539.aspx