Adding to WordprocessingDocument opened from MemoryStream without getting "Memory stream is not expandable"?
Asked Answered
C

1

6

Using Open XML SDK, the following gives "Memory stream is not expandable" when I reach the line FeedData(msData):

// Bytes in, bytes out
internal static byte[] UpdateDataStoreInMemoryStream(byte[] bytes,
   XmlDocument xdocData)
{
   using (var msDoc = new MemoryStream(bytes))
   {
      using (WordprocessingDocument wd = WordprocessingDocument.Open(msDoc, true))
      {
         MainDocumentPart mdp = wd.MainDocumentPart;
         CustomXmlPart cxp = mdp.CustomXmlParts.SingleOrDefault<CustomXmlPart>();
         using (MemoryStream msData = new MemoryStream())
         {
            xdocData.Save(msData);
            msData.Position = 0;
            // Replace content of ...\customXml\item1.xml. 
            cxp.FeedData(msData);
            // "Memory stream is not expandable" if more data than was there initially.
         }
      }
      return msDoc.ToArray();
   }
}

Note: it is not msData that is the trouble but msDoc.

Stein-Tore

Cauline answered 14/12, 2013 at 22:33 Comment(0)
C
13

The trouble was (actually quite obvious from the error message) that

using (var msDoc = new MemoryStream(bytes)) ...

creates a fixed size MemoryStream. So solution is to create an expandable MemoryStream:

MemoryStream msDoc = new MemoryStream();
msDoc.Write(bytes, 0, bytes.Length);
msDoc.Position = 0;
...
Cauline answered 21/12, 2013 at 6:25 Comment(1)
Did the change. Now when I open my Document in SharePoint-Online and take a look at the print preview I get an Blue Screen :DHildehildebrand

© 2022 - 2024 — McMap. All rights reserved.