Skip to content

Commit

Permalink
Fix failure to dispose stream when exception occurs in Package.Open (d…
Browse files Browse the repository at this point in the history
…otnet#46796)

* Fix packaging bug

* Update Tests.cs

* CR feedback
  • Loading branch information
danmoseley authored Jan 14, 2021
1 parent 145467d commit 2c1cb08
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -282,10 +282,8 @@ internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFil
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
zipArchive?.Dispose();
_containerStream?.Dispose();

throw;
}
Expand Down
20 changes: 20 additions & 0 deletions src/libraries/System.IO.Packaging/tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,26 @@ public void PackageOpen_Open_EmptyStream_Throws()
}
}

[Fact]
public void PackageOpen_Open_InvalidContent_Throws()
{
string temp = GetTempFileInfoWithExtension(".docx").FullName;

using (FileStream fs = File.OpenWrite(temp))
{
byte[] bytes = File.ReadAllBytes("plain.docx");
bytes.AsSpan(500, 500).Clear(); // garble it
fs.Write(bytes, 0, bytes.Length);
}

AssertExtensions.ThrowsAny<InvalidDataException, ArgumentOutOfRangeException>(
() => Package.Open(temp, FileMode.Open, FileAccess.Read, FileShare.Read));

// Package should not have held a stream open on the file; if it did, this operation will
// throw IOException (unless the finalizer runs first, and it will not do so deterministically)
File.Move(temp, GetTestFilePath());
}

[Fact]
public void T172_EmptyRelationshipPart()
{
Expand Down

0 comments on commit 2c1cb08

Please sign in to comment.