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

Stein-Tore Erdal
  • 473
  • 1
  • 6
  • 15

1 Answers1

12

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;
...
Stein-Tore Erdal
  • 473
  • 1
  • 6
  • 15
  • 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 :D – axbeit Apr 15 '21 at 16:54