How To Merge Two FlowDocument Objects Using C# Code[WPF]
As part of one of requirements in our application we had to appended a FlowDocument objects to another FlowDocument object. The requirement looked very simple and I tried the following which loops through the Blocks of source FlowDocument and appends them to target FlowDocument object.
sourceDocument = (FlowDocument)XamlReader.Load(memoryStream); // foreach (Block aBlock in sourceDocument.Blocks) { targetDocument.Blocks.Add(aBlock); }
But the above code broke with this exception
An exception of type ‘System.InvalidOperationException’ occurred and was caught. Collection was modified; enumeration operation may not execute.
Not sure the reason why the exception is raising when we loop through the Blocks of FlowDocument and add them to the another FlowDocument. But i resolved the issue by converting the Blocks of source object to List and then adding them to the target FlowDocument. Here is the code that worked
// sourceDocument = (FlowDocument)XamlReader.Load(memoryStream); // List<Block> flowDocumentBlocks = new List<Block>(sourceDocument.Blocks);
// foreach (Block aBlock in flowDocumentBlocks) { targetDocument.Blocks.Add(aBlock); }
Hope this piece of code helps you.
Simillar Posts
- Microsoft Excel Tip – How To Convert Columns To Rows And Vice Versa
- How To Fix “MSDTC on server ‘server name’ is unavailable” Error[ASP.NET/SQL Server]
- Fixing LINQ Error “Sequence contains no elements” [C#, LINQ]
- Code Snippets In Google Search Results
- How To Define Conditional Compilation Symbols In MSBuild Automated C# Compilations [Programming]

March 4th, 2009
Yup, found the same thing. Doesn’t seem to make a lot of sense, but this gets by the error. Thanks for posting!
June 1st, 2009
… a guess why the original code did not work – According to MSDN, to manipulate or enumerate the contents of the Blocks-property, one should be targetting the BlockCollection that the Blocks-property return, not the actual Blocks-property.
http://msdn.microsoft.com/en-us/library/system.windows.documents.blockcollection.aspx
June 1st, 2009
(or so I interpret this remark, from the FlowDocument.Blocks Property-page):
“Use the BlockCollection returned by this property to enumerate or manipulate contents of a FlowDocument.”