2

I am using the following code to create a MS word document using OpenXML WordprocessingDocument from a word template.I am using Stream and not using any physical location for new document.Using OpenXML ,Is is possible to create document without using a physical location (only with Stream) and finally save to a location?

I am not getting any error and new document is created successfully but the newly created document is corrupted and unable to open in MS word.

using (Stream stream1 = new FileStream("c:\\TestDoc.dotx", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) {
    using (WordprocessingDocument document = WordprocessingDocument.Open(stream1, true)) {
        document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
        MainDocumentPart mainPart = document.MainDocumentPart;
        DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart;
        mainPart.Document.Save();

        Stream mystream =  mainPart.GetStream();                        
        FileStream fileStream = File.Create("c:\\newdoc.docx", (int)mystream.Length);
        byte[] bytesInStream = new byte[mystream.Length];
        mystream.Read(bytesInStream, 0, bytesInStream.Length);
        fileStream.Write(bytesInStream, 0, bytesInStream.Length);

        document.Close();
    }
}
user32124
  • 23
  • 8
  • I don't see any memory stream here? You're also only writing the 'main' part to your target file, not the whole of your word document (which is made up of far more than a single XML file - it's a zip container with multiple files in it). – Charles Mager Jul 14 '16 at 09:52
  • Hi Charles, How can I get whole new document inside Memory Stream.I do not want to use any physical location (destination) during the process.This is a test code where I'm checking if file is created onto c: drive.I wanted to do some more activity with Memory Stream ,so need to get Memory Stream of newly created doc – user32124 Jul 14 '16 at 09:59
  • 1
    Possible duplicate of [Save modified WordprocessingDocument to new file](http://stackoverflow.com/questions/8818160/save-modified-wordprocessingdocument-to-new-file) – Charles Mager Jul 14 '16 at 10:00

0 Answers0