diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.cs index cb4c250cec555..a3d7c5cce0665 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.cs @@ -127,7 +127,20 @@ public Icon(Stream stream, int width, int height) : this() ArgumentNullException.ThrowIfNull(stream); _iconData = new byte[(int)stream.Length]; - stream.Read(_iconData, 0, _iconData.Length); +#if NET7_0_OR_GREATER + stream.ReadExactly(_iconData); +#else + int totalRead = 0; + while (totalRead < _iconData.Length) + { + int bytesRead = stream.Read(_iconData, totalRead, _iconData.Length - totalRead); + if (bytesRead <= 0) + { + throw new EndOfStreamException(); + } + totalRead += bytesRead; + } +#endif Initialize(width, height); } diff --git a/src/libraries/System.Drawing.Common/tests/IconTests.cs b/src/libraries/System.Drawing.Common/tests/IconTests.cs index fae209c336dfb..249d17065b930 100644 --- a/src/libraries/System.Drawing.Common/tests/IconTests.cs +++ b/src/libraries/System.Drawing.Common/tests/IconTests.cs @@ -113,6 +113,23 @@ public void Ctor_Stream() } } + [ConditionalFact(Helpers.IsDrawingSupported)] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug fix in core")] + public void Ctor_Stream_Trickled() + { + var stream = new TrickleStream(File.ReadAllBytes(Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico"))); + var icon = new Icon(stream); + Assert.Equal(32, icon.Width); + Assert.Equal(32, icon.Height); + Assert.Equal(new Size(32, 32), icon.Size); + } + + private sealed class TrickleStream : MemoryStream + { + public TrickleStream(byte[] bytes) : base(bytes) { } + public override int Read(byte[] buffer, int offset, int count) => base.Read(buffer, offset, Math.Min(count, 1)); + } + [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Size_TestData))] public void Ctor_Stream_Width_Height(string fileName, Size size, Size expectedSize)