In C#, I’m trying to save a Pdf to a MemoryStream and then convert the stream to an array of bytes (to save to a database). However, at the point where I call the .Save method on the Pdf I get a ‘Cannot access a closed Stream’ exception, even on a stream that I’ve just created.
Here’s my code:
public byte[] generatePdf()
{
Pdf masterDocument = new Pdf();
// Do document generation here...
byte[] documentBytes;
using (MemoryStream documentStream = new MemoryStream())
{
// This line throws the 'Cannot access a closed Stream' exception
masterDocument.Save(documentStream);
documentBytes = documentStream.ToArray();
}
return documentBytes;
}
Is there something I’m doing incorrectly?