Best way to save document to stream

Hi,


Can you tell me what is the best way to update a Aspose.Word.Document created from a stream passed in parameter to a method please ??

Here wath i’ve done :

private void addWatermark(Stream fileStream, string watermarkText)
{
Aspose.Words.Document doc = new Aspose.Words.Document(fileStream);

… some processes …

doc.Save(fileStream, Aspose.Words.SaveFormat.Docm);
}

If i do that, my file is corrupted. But if i save the document into another file like that :
doc.Save(@“C:\Users\User\Documents\test.docm”, Aspose.Words.SaveFormat.Docm);
It works !

Is it not possible to save changes to the same stream that the source?

Thanks !

Kevin

Hi Kevin,

Thanks for your inquiry.

It is probably not a good idea to use same stream for opening and then saving the document before the opened stream is not closed. You can use MemoryStream to save your data and then manipulate it further or use it in your logic according to your requirements. Here is the code snippet for your reference:
    MemoryStream ms = new MemoryStream();
    doc.Save(ms, SaveFormat.Docm);
    byte[] data = ms.ToArray();
    File.WriteAllBytes("C:\\Temp\\test.docm", data);
You can also send the MemoryStream object in your method as a reference parameter so that you can save changes in it and caller will have the in memory data of document with processing performed. Additionally you can also create Stream object of input and output separately for the same document but you will have to close input stream before opening the output stream for same file.
For further details of MemoryStream usage with Aspose.Words, please have a look here. Hope this helps. Please feel free to ask if you have any more queries.