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

时光总嘲笑我的痴心妄想 提交于 2019-12-05 02:31:42

问题


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


回答1:


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;
...


来源:https://stackoverflow.com/questions/20589020/adding-to-wordprocessingdocument-opened-from-memorystream-without-getting-memor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!