From 6a5f84285d4595be49bd34ef511e136b80fd49e5 Mon Sep 17 00:00:00 2001 From: guangyu2002 <53631965+guangyu2002@users.noreply.github.com> Date: Wed, 17 Jul 2024 14:19:02 +0800 Subject: [PATCH] Update IOUtils.cs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正ToByteArray方法中ByteArrayOutputStream未释放的bug --- main/Util/IOUtils.cs | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/main/Util/IOUtils.cs b/main/Util/IOUtils.cs index 6c00ecc11..5cec5747d 100644 --- a/main/Util/IOUtils.cs +++ b/main/Util/IOUtils.cs @@ -129,26 +129,27 @@ public static byte[] ToByteArray(Stream stream) /// public static byte[] ToByteArray(Stream stream, int length) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(length == Int32.MaxValue ? 4096 : length); - - byte[] buffer = new byte[4096]; - int totalBytes = 0, readBytes; - do + using (ByteArrayOutputStream baos = new ByteArrayOutputStream(length == Int32.MaxValue ? 4096 : length)) { - readBytes = stream.Read(buffer, 0, Math.Min(buffer.Length, length - totalBytes)); - totalBytes += Math.Max(readBytes, 0); - if (readBytes > 0) + byte[] buffer = new byte[4096]; + int totalBytes = 0, readBytes; + do + { + readBytes = stream.Read(buffer, 0, Math.Min(buffer.Length, length - totalBytes)); + totalBytes += Math.Max(readBytes, 0); + if(readBytes > 0) + { + baos.Write(buffer, 0, readBytes); + } + } while(totalBytes < length && readBytes > 0); + + if(length != Int32.MaxValue && totalBytes < length) { - baos.Write(buffer, 0, readBytes); + throw new IOException("unexpected EOF"); } - } while (totalBytes < length && readBytes > 0); - - if (length != Int32.MaxValue && totalBytes < length) - { - throw new IOException("unexpected EOF"); + + return baos.ToByteArray(); } - - return baos.ToByteArray(); } public static byte[] ToByteArray(ByteBuffer buffer, int length)