diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs index 81d90e1d7be21..fcc5d22cde60e 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs @@ -629,7 +629,7 @@ private int WriteCommonFields(Span buffer, TarEntryType actualEntryType) checksum += FormatNumeric(_gid, buffer.Slice(FieldLocations.Gid, FieldLengths.Gid)); } - if (_size > 0) + if (_dataStream != null && _size >= 0) { checksum += FormatNumeric(_size, buffer.Slice(FieldLocations.Size, FieldLengths.Size)); } diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.Tests.cs index b46816844b44c..cb65c0e6d163e 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.Tests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.IO; +using System.Linq; using Xunit; namespace System.Formats.Tar.Tests @@ -350,5 +351,20 @@ private int GetChecksumForFormatSpecificFields(TarEntry entry, TarEntryFormat fo // Gnu BlockDevice: 623 + 1004 + 686 + 1142 = 3455 return checksum; } + + [Fact] + void Verify_Size_RegularFile_Empty() + { + using MemoryStream emptyData = new(0); + using MemoryStream output = new(); + using TarWriter archive = new(output, TarEntryFormat.Pax); + PaxTarEntry te = new(TarEntryType.RegularFile, "zero_size") + { DataStream = emptyData }; + archive.WriteEntry(te); + var sizeBuffer = output.GetBuffer()[1148..(1148 + 12)]; + // we expect ocal zeros + byte[] expected = [0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0]; + Assert.True(sizeBuffer.SequenceEqual(expected)); + } } }