Skip to content

Commit 5090041

Browse files
authored
TarReader should dispose underlying stream if leaveOpen is false (#79899)
1 parent 48e7418 commit 5090041

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarReader.cs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public TarReader(Stream archiveStream, bool leaveOpen = false)
4848
}
4949

5050
/// <summary>
51-
/// Disposes the current <see cref="TarReader"/> instance, and disposes the non-null <see cref="TarEntry.DataStream"/> instances of all the entries that were read from the archive.
51+
/// Disposes the current <see cref="TarReader"/> instance, closes the archive stream, and disposes the non-null <see cref="TarEntry.DataStream"/> instances of all the entries that were read from the archive if the <c>leaveOpen</c> argument was set to <see langword="false"/> in the constructor.
5252
/// </summary>
5353
/// <remarks>The <see cref="TarEntry.DataStream"/> property of any entry can be replaced with a new stream. If the user decides to replace it on a <see cref="TarEntry"/> instance that was obtained using a <see cref="TarReader"/>, the underlying stream gets disposed immediately, freeing the <see cref="TarReader"/> of origin from the responsibility of having to dispose it.</remarks>
5454
public void Dispose()
@@ -57,11 +57,16 @@ public void Dispose()
5757
{
5858
_isDisposed = true;
5959

60-
if (!_leaveOpen && _dataStreamsToDispose?.Count > 0)
60+
if (!_leaveOpen)
6161
{
62-
foreach (Stream s in _dataStreamsToDispose)
62+
_archiveStream.Dispose();
63+
64+
if (_dataStreamsToDispose?.Count > 0)
6365
{
64-
s.Dispose();
66+
foreach (Stream s in _dataStreamsToDispose)
67+
{
68+
s.Dispose();
69+
}
6570
}
6671
}
6772
}

src/libraries/System.Formats.Tar/tests/TarReader/TarReader.Tests.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ public void TarReader_LeaveOpen_False()
3838
}
3939
}
4040

41+
Assert.Throws<ObjectDisposedException>(() => ms.ReadByte());
42+
4143
Assert.True(dataStreams.Any());
4244
foreach (Stream ds in dataStreams)
4345
{
@@ -62,6 +64,8 @@ public void TarReader_LeaveOpen_True()
6264
}
6365
}
6466

67+
ms.ReadByte(); // Should not throw
68+
6569
Assert.True(dataStreams.Any());
6670
foreach (Stream ds in dataStreams)
6771
{

0 commit comments

Comments
 (0)