Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream into package, package into WordDocument and then back again

I do not understand all the mechanics surrounding Streams and even less around the System.IO.Package class.

I have a .docx document as a binary in a DataBase and I wan't to fetch it, modify somewhat and then save it.

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

This 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);
}

With the library code going 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 just comes out just as it was saved into the DB without all the extra data added in.

I assumed as I opened the Package with a memory stream all the changes to the package would be saved into the stream as well.

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

EDIT

I was wrong, there isn't anything broken with my code. Problem was that someIrreleventData part was null and both the fetcher there and the code inside FillTemplate method didn't handle the exception correctly.

like image 225
Ingó Vals Avatar asked Jul 22 '11 16:07

Ingó Vals


1 Answers

I don't see any place where you call Flush() and/or Close() on the Package before trying to save it to file...
try changing

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 should call document.Close() .

Calling .Dispose() is a good idea though it would even be better if you used as using block which takes care of that and several other things...

like image 88
Yahia Avatar answered Sep 28 '22 18:09

Yahia