开发者

Loading binary file from db and process it as openxml

I have such method to load document file from db that is stored as binary and then replace customxml parts with parameters.

Somehow when i convert byte into MemoryStream then process it doesn't work, my custom xml parts are not replaced. But if i use FileStream and read same file from disk then it replaced perfectly!

What is wrong with MemoryStream? i can't also cast MemoryStream to FileStream or create instrance of Stream or etc.. Any suggestion?

  private static Stream LoadContent(byte[] content, XmlDocument parameters)
   开发者_运维百科 {
        //FileStream works perfectly
        //Stream fileStream = new FileStream(@"C:\temp\test.docx", FileMode.Open);

        Stream documentStream = new MemoryStream();
        documentStream.Write(content, 0, content.Length);

        //Processes word file, replace custom xml parts with parameters
        using (WordprocessingDocument document = WordprocessingDocument.Open(documentStream, true))
        {
            MainDocumentPart mainPart = document.MainDocumentPart;
            Stream partStream = mainPart.CustomXmlParts.First().GetStream();

            using (XmlWriter xmlWriter = XmlWriter.Create(partStream, new XmlWriterSettings { CloseOutput = false }))
            {
                parameters.WriteTo(xmlWriter);
                xmlWriter.Flush();
            }

            mainPart.Document.Save();
        }

        return documentStream;
    }


You might want to try to set the 'Position' propery of the memorystream to 0 after writing data to it and before reading it again.

Alernatively you can also pass the byte array to the constructor of the memorystream instead of calling writer.

edit

I see according to MSDN that the 'Document.Save' method will flush the stream to allow propper saving. ( http://msdn.microsoft.com/en-us/library/cc840441.aspx ). However MemoryStream wont do anything on flush ( http://msdn.microsoft.com/en-us/library/system.io.memorystream.flush.aspx ).

You could try to create a new MemoryStream and then pass that as a parameter to the 'Document.Save' method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜