Cannot access a closed stream, at System.IO.MemoryStream.get_Position()

Hi,

i m trying to convert a aspose.Pdf.Document I generated to byteArray , however while saving the doc I get this error, I tried all the fixes suggested in different platforms

///this is how i process the forms to genereate Pdf.document -

public static byte[] ProcessForms(FormFieldPrintMapper formFieldPrintMapper, FormTemplate template, String diagModePath, String timeZoneId, List<FormField> formFields)
        {
            List<IForm> forms = new List<IForm>();
            Aspose.Pdf.Document mergeDocument = new Aspose.Pdf.Document();
          
            
                IForm f = null;
 
                if (template.FileType.ToUpper().Equals("PDF"))
                {
                    f = new PdfForm();
                }
                else
                {
                    //  f = new DocForm(); // TODO: need to uncomments as the file is included.
                }
 
                forms.Add(f);
 
                f.Merge(mergeDocument, formFieldPrintMapper, template.Copies.HasValue ? template.Copies.Value : 0, template, timeZoneId, formFields);
            //}
 
            byte[] bytes = GetReturnFile(mergeDocument, diagModePath);
 
            foreach (IForm form in forms)
            {
                form.Dispose();
            }
 
            mergeDocument.Dispose();
            return bytes;
        }

// Merge

public void Merge(Document outputDocument, FormFieldPrintMapper fieldMapper, Int32 copies, FormTemplate rawForm, String timeZoneId, List<FormField> result)
        {
            if (rawForm.Form != null)
            {
                PageCollection pages;
                using (MemoryStream stream = new MemoryStream())
                {
                    stream.Write(rawForm.Form, 0, rawForm.Form.Length);
 
                    // The inheriting type will open this into the appropriate document type (PDF or DOC)
                    this.Open(stream);
 
                    // gets the fields from the document using a token
                    var docFields = this.GetFields();
 
                    // Get the defined fields from the database
                    //var templateFields = context.FormFieldSet;
                    SetFormFieldValues(fieldMapper, timeZoneId, docFields, result);
 
                    // once the fields are all set, re-save the OpenXml document back to it's own stream
                    pages = this.Save(stream);
 
                    stream.Close();
                }
 
                // append the pages from the pdf to the master document for as many copies as requested
                for (int i = 0; i < copies; i++)
                {
                    outputDocument.Pages.Add(pages);
                }
            }
        }

// I get the error here- mergeDocument.Save
private static byte[] GetReturnFile(Aspose.Pdf.Document mergeDocument, string diagModePath)
{
byte[] result = null;

            // saves the file for debugging purposes in both formats prior to returning the stream.
            if (!String.IsNullOrEmpty(diagModePath))
            {
                var pdfName = string.Format(@"{0}\{1}.pdf", diagModePath, DateTime.Now.ToOADate().ToString());
                mergeDocument.Save(pdfName);
 
                var docName = string.Format(@"{0}\{1}.doc", diagModePath, DateTime.Now.ToOADate().ToString());
                mergeDocument.Save(docName, SaveFormat.Doc);
            }
 
            using (MemoryStream outStream = new MemoryStream())
            {
                mergeDocument.Save(outStream);
                result = outStream.ToArray();
            }
 
            return result;
        }

Exception:

at System.IO.MemoryStream.get_Position()
at � .Read(Byte[] �, Int32 �, Int32 �)
at � .�.�(� �, � �, Boolean �, Int64& �)
at � .�.� �(� �, � �)
at � .�(� �, � �, Boolean �, Int64& �)
at � .� �(� �, � �)
at � .�.�(� �, � �, Boolean �, Int64& �)
at � .�.� �(� �, � �, Int64& �)
at � .�(� �, � �, Boolean �, Int64& �)
at � .� �(� �, � �, Int64& �)
at � .� �(� �, � �)
at � .� �(Stream �)
at � .� �(Stream �)
at Aspose.Pdf.Document.�(Stream �, SaveOptions �)
at Servpro.Evergreen.Application.Forms.FormsManager.GetReturnFile(Document mergeDocument, String diagModePath) in C:\GitKraken_New7\franchise-

Error message - Cannot access a closed stream.

Kindly help

@PatrickCook

Thanks for contacting support.

We have observed the code snippet that you have shared as well the exception description. By looking at the exception message it seems it is occurring while you are calling Save() method second time for saving Document as DOC format.

Please note that Document.Save() method behaves more like Disposing the document as it clears all used/using resources which are loaded into memory for Document processing. While saving document needs closed/cleared resources again hence, results in an exception. In order to prevent such issue, you need to re-initialize document object from saved file path or some MemoryStream so that you can re-save it with other format.

We hope that shared information would be helpful however, if issue still persists, we request you to please share simplified code snippet along with sample PDF document(s). We will test the scenario in our environment and address it accordingly.