Yoda
Yoda

Reputation: 18068

How to prevent closing stream when returning File result?

I'm trying to return a file to browser, unfortunately I get an error:

System.ObjectDisposedException: Cannot access a closed Stream. at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count) at System.IO.MemoryStream.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)

My controller action is:

public IActionResult DownloadBarcode(Guid barcodeId)
    {
        var currentUserId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
        var barcode = _context.Barcodes.Find(barcodeId);
        
        var myBarcode = QRCodeWriter.CreateBarcode(barcode.Value);
        myBarcode.AddAnnotationTextBelowBarcode(barcode.Value);
        var stream = myBarcode.ToPdfStream();
        return File(stream, "application/pdf", $"etykieta{barcodeId}.pdf");
    }

The underlying 3rd party ToPdfStream() doesn't close the stream and sets Position to 0.

 public Stream ToPdfStream()
        {
            PdfDocument pdfDocument = new PdfDocument(generateUniqueDocumentIdentifiers: true);
            Bitmap innerBitmap = InnerBitmap;
            PdfPage pdfPage = pdfDocument.AddPage();
            pdfPage.Width = innerBitmap.Width;
            pdfPage.Height = innerBitmap.Height;
            pdfPage.TrimMargins.All = 0;
            DrawImage(XGraphics.FromPdfPage(pdfPage), innerBitmap, 0, 0);
            using Stream stream = new MemoryStream();
            pdfDocument.Save(stream, closeStream: false);
            return stream;
        }

Upvotes: 0

Views: 790

Answers (1)

Amir Tahan
Amir Tahan

Reputation: 129

You can see this awnser... Remove using in your ToPdfStream methode and use (using) in your DownloadBarcode action... That do the same thing and your problem should be fixed.

Upvotes: 0

Related Questions