xceedsoftware / DocX

Fast and easy to use .NET library that creates or modifies Microsoft Word files without installing Word.
Other
1.78k stars 475 forks source link

InsertParagraphAfterSelf throws an error after update to v2.5.0 or v3.0.0 #474

Open CGarvizu opened 8 months ago

CGarvizu commented 8 months ago

I was using the InsertParagraphAfterSelf method of Paragraph to insert paragraphs from one document to another without issues until release 2.4 (including 2.4.1), but the code is now throwing an error if I update DocX to 2.5.0 or the latest 3.0.0

Collection was modified; enumeration operation may not execute.

The release notes of 2.5.0 state:

In Paragraph, using the InsertParagraphAfterSelf or InsertParagraphBeforeSelf methods no longer breaks the Paragraphs collection.

Is there a chance there is a regression?

My code (edited) is next; InsertParagraphAfterSelf(paragraph) is successful the first time, but the next iteration always throws the above-referenced error.

foreach (var par in subdocument.Paragraphs)
{
    if (par.Hyperlinks.Count > 0)
    {
        Paragraph paragraph = template.InsertParagraph();
        foreach (var magicWord in par.MagicText)
            if (string.Equals(magicWord.formatting?.StyleId?.ToLower(), "hyperlink"))
            {
                paragraph.InsertText(string.Concat("[[", magicWord.text, "]]"), false, magicWord.formatting);
            }
            else
                paragraph.InsertText(magicWord.text, false, magicWord.formatting);

        bookmarkParagraph = bookmarkParagraph.InsertParagraphAfterSelf(paragraph);
    }
    else
    {
        bookmarkParagraph = bookmarkParagraph.InsertParagraphAfterSelf(par);
    }
}

Thanks!

XceedBoucherS commented 7 months ago

Hello, Sorry for the delay.

Is this still an issue in the latest v3.0.0 version from NuGet ? I've updated your sample to be able to run it and I saw no exception. I attached my test.docx file.

Here's the sample I used : var subdocument = DocX.Load( "test.docx" ); var template = DocX.Create( "output.docx" ); Paragraph bookmarkParagraph = template.InsertParagraph();

foreach( var par in subdocument.Paragraphs ) { if( par.Hyperlinks.Count > 0 ) { Paragraph paragraph = template.InsertParagraph();

foreach( var magicWord in par.MagicText )
{
  if( string.Equals( magicWord.formatting?.StyleId?.ToLower(), "hyperlink" ) )
  {
    paragraph.InsertText( string.Concat( "[[", magicWord.text, "]]" ), false, magicWord.formatting );
  }
  else
  {
    paragraph.InsertText( magicWord.text, false, magicWord.formatting );
  }
}

bookmarkParagraph = bookmarkParagraph.InsertParagraphAfterSelf( paragraph );

} else { bookmarkParagraph = bookmarkParagraph.InsertParagraphAfterSelf( par ); } }

template.Save(); test.docx

Thank you