views:

115

answers:

1

I have 2 snippets of code which work differently

using (WordprocessingDocument wordDocument =
           WordprocessingDocument.Create(@"D:\Tests\WordML\ML_Example.docx", WordprocessingDocumentType.Document))
        {
            // Add a main document part. 
            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
            TextReader tr = new StreamReader("SimpleTextExample.xml");
            mainPart.Document = new Document(tr.ReadToEnd());
        }

Here it works great and generates .docx good.

Now second way of making it with bytes and MemoryStream-uri.

 MemoryStream modeleRootStream = new MemoryStream();

XmlWriterSettings writerSettings = new XmlWriterSettings { OmitXmlDeclaration = true }; XmlWriter xmlWriter = XmlWriter.Create(modeleRootStream, writerSettings);

        initialXml.WriteTo(xmlWriter);

        xmlWriter.Flush();

        modeleRootStream.Position = 0;
       MemoryStream streamWithWord = new MemoryStream();

        using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(streamWithWord,
            WordprocessingDocumentType.Document))
        {
            // Add a main document part. 
            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

            string streamContent = string.Empty;

            using (StreamReader reader = new StreamReader(modeleRootStream))
            {
               streamContent = reader.ReadToEnd();
            }

            mainPart.Document = new Document(streamContent);
        }

        byte[] wordDocBytes = streamWithWord.GetBuffer();

        streamWithWord.Close();

        File.WriteAllBytes(@"D:\Tests\WordML\ML_Example1.docx", wordDocBytes);

When you make it 2nd way the generated document is not good. In it's document.xml you're gonna see xml declaration. The initialXml represents XElement of initial WordML xml.

<?xml version="1.0" encoding="utf-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"&gt;

....

And when you try to open it in Word it gives you the message that the file is truncated.

How can I use bytes and MemoryStreams and not have this issue.

+1  A: 

This is wrong:

byte[] wordDocBytes = streamWithWord.GetBuffer();

That should be:

byte[] wordDocBytes = streamWithWord.ToArray();

GetBuffer returns the extra part of the buffer - not just the valid data.

You can usually omit xml headers with XmlWriterSettings.

It is almost certainly to do the write more directly, but I'm about to run out of signal (on the train...).

Marc Gravell