添加到从MemoryStream打开的WordprocessingDocument而不会得到"内存流不可扩展"?

时间:2013-12-14 22:33:22

标签: openxml-sdk

使用Open XML SDK,当我到达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();
   }
}

注意:问题不是msData,而是msDoc。

的Stein-撕

1 个答案:

答案 0 :(得分:11)

问题是(实际上从错误信息中很明显)

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

创建一个固定大小的MemoryStream。 所以解决方案是创建一个可扩展的MemoryStream:

MemoryStream msDoc = new MemoryStream();
msDoc.Write(bytes, 0, bytes.Length);
msDoc.Position = 0;
...