Stream to package, package to WordDocument, and then back

I don’t understand all the mechanics around Streams and even less around the System.IO.Package class.

I have a .docx document as a binary in the database, and I do not want to extract it, modify it a bit, and then save it.

I currently have a method that modifies a document in a separate library, because it will be used in many places.

Here is how I tried to do this:

 byte[] doc = getDocFromDB(); using (MemoryStream mem = new MemoryStream()) { mem.Write(doc, 0, doc.Length); Package pack = Package.Open(mem, FileMode.Open, FileAccess.ReadWrite); filler.FillTemplate(ref pack, someIrreleventData); string filePath = Path.GetTempPath() + "docname.docx"; using (FileStream file = new FileStream(filePath, FileMode.Create)) { mem.WriteTo(file); file.Flush(); file.Close(); } Process.Start(filePath); } 

When the library code looks something like this:

 public void FillTemplate(ref Package package, XElement data) { WordprocessingDocument document = WordprocessingDocument.Open(package); //add the data to the document //should I do document.close() or document.dispose() here? } 

The document simply appears as soon as it was saved in the database without adding additional data.

I assumed that by opening a package with a memory stream, all changes in the package will also be saved in the stream.

What am I doing wrong and how can I do it better.

EDIT

I was mistaken, nothing is broken with my code. The problem was that part of somerreleventData was null, and there was a receiver, and the code inside the FillTemplate method did not correctly handle the exception.

+7
source share
1 answer

I do not see the place where you call Flush() and / or Close() in the Package before trying to save it to a file ...
try to change

 mem.Write(doc, 0, doc.Length); mem.Position = 0; // new, perhaps this is relevant for Package.Open ? Package pack = Package.Open(mem, FileMode.Open, FileAccess.ReadWrite); filler.FillTemplate(ref pack, someIrreleventData); pack.Flush(); pack.Close(); // new mem.Position = 0; // new 

And: yes, you have to call document.Close() .

Calling .Dispose() is a good idea, although it would be even better if you used it as a using block that takes care of this and some other things ...

+4
source

All Articles