Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

openxml-sdk

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

like image 513
Stein-Tore Erdal Avatar asked Dec 14 '13 22:12

Stein-Tore Erdal


1 Answers

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;
...
like image 195
Stein-Tore Erdal Avatar answered Oct 26 '22 14:10

Stein-Tore Erdal