When saving the file to memory stream the stream get disposed or closed.
Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
doc.PageInfo = pageInfo;
//// some more codes to ad details in pageinfo
using (MemoryStream oms = new MemoryStream())
{
doc.Save(oms); //here we are getting the error
///
}
exception message: Cannot access a closed Stream.
version 23.5
We could not replicate the exception in our environment with the latest version of the API. Can you please make sure that pageinfo
object in your code does not belong to an already disposed object? Also, please try to use the 23.9 version of the API and let us know if issue still persists.
@asad.ali
Thanks for the reply.
We are experiencing this issue intermittently. If I call these method 5 times, I encounter the issue at least once. pageinfo, page, tables, rows, cells were used in between these codes all are new objects .
It is quite hard to replicate this scenario in our environment as issue is intermittent. It is highly possible that it is happening due to calling a disposed object in your lengthy code routine. If possible, can you please share a sample console application with instructions to reproduce the issue? We will further proceed to assist you accordingly.
there are some memorystreams which are not closed will that cause any problem.
public static void Run()
{
byte[] imagebytecode = getimagecode(); //generating barcode image
Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
///code for adding tables rows cells
Cell cell1 = row1.Cells.Add();
cell1.Paragraphs.Add(ImgTemplate(imagebytecode));// ImgTemplate method called mutiple times
using (MemoryStream oms = new MemoryStream())
{
doc.Save(oms);
}
}
private static Image ImgTemplate(byte[] imageData)
{
Image image = new Image();
image.ImageStream = new MemoryStream(imageData);
return image;
}
In your code, you are creating multiple MemoryStream objects for the image streams, but you are not disposing them properly. This may cause memory leaks and unexpected errors. You should either wrap them in using statements, or call the Dispose method explicitly when you are done with them. For example:
private static Image ImgTemplate(byte[] imageData)
{
Image image = new Image();
using (MemoryStream ms = new MemoryStream(imageData))
{
image.ImageStream = ms;
return image;
}
}
Alternatively, you can save the image data to a file and use the Image.File property instead of the Image.ImageStream property. For example:
private static Image ImgTemplate(byte[] imageData)
{
Image image = new Image();
string imagePath = "image.jpg";
File.WriteAllBytes(imagePath, imageData);
image.File = imagePath;
return image;
}
I found the reason it’s causing issues. The problem was that the ‘IsBlackWhite’ setting was originally set to ‘true.’ After changing it to ‘false,’ it is now working correctly.
image.IsBlackWhite = false;
It is nice to know that your issue is resolved now. Please feel free to create a new topic in case you face any other issues.