From 3abe210c6f517259b3d6764c27ac583a99f20119 Mon Sep 17 00:00:00 2001 From: InusualZ Date: Sat, 14 Mar 2020 09:49:53 -0400 Subject: [PATCH] Add new flag to control, weather we want to dispose the base stream. Let the base stream throw in case of using unsupported method (Ex. Seek, Read, etc..) --- src/UglyToad.PdfPig/Writer/PdfStreamWriter.cs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/UglyToad.PdfPig/Writer/PdfStreamWriter.cs b/src/UglyToad.PdfPig/Writer/PdfStreamWriter.cs index ac0f9d47..d4b7f038 100644 --- a/src/UglyToad.PdfPig/Writer/PdfStreamWriter.cs +++ b/src/UglyToad.PdfPig/Writer/PdfStreamWriter.cs @@ -20,11 +20,14 @@ public Stream Stream { get; private set; } + public bool DisposeStream { get; set; } + public PdfStreamWriter() : this(new MemoryStream()) { } - public PdfStreamWriter(Stream baseStream) + public PdfStreamWriter(Stream baseStream, bool disposeStream = true) { Stream = baseStream ?? throw new ArgumentNullException(nameof(baseStream)); + DisposeStream = disposeStream; } public void Flush(decimal version, IndirectReferenceToken catalogReference) @@ -110,15 +113,11 @@ public byte[] ToArray() { - if (!Stream.CanSeek) - throw new NotSupportedException($"{Stream.GetType()} can't seek"); - var currentPosition = Stream.Position; Stream.Seek(0, SeekOrigin.Begin); var bytes = new byte[Stream.Length]; - // Should we slice the reading into smaller chunks? if (Stream.Read(bytes, 0, bytes.Length) != bytes.Length) throw new Exception("Unable to read all the bytes from stream"); @@ -129,6 +128,12 @@ public void Dispose() { + if (!DisposeStream) + { + Stream = null; + return; + } + Stream?.Dispose(); Stream = null; }