Skip to content

Commit 2917190

Browse files
committed
Add leaveOpen parameter to ReadToEnd methods
Updated the `ReadToEnd` and `ReadToEndAsync` methods in the `StreamExtensions` class to include a `leaveOpen` boolean parameter. This allows the caller to control whether the stream remains open after reading. If set to `false`, the stream will be disposed. XML documentation comments have been added to describe the new parameter.
1 parent bad4bce commit 2917190

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

Sources/EasyExtensions/Extensions/StreamExtensions.cs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,29 +14,41 @@ public static class StreamExtensions
1414
/// <summary>
1515
/// Reads the bytes from the current stream and writes them to the byte array.
1616
/// </summary>
17+
/// <param name="stream"> The stream to read from. </param>
18+
/// <param name="leaveOpen"> If true, the stream will not be disposed after reading. </param>
1719
/// <returns> Received byte array. </returns>
1820
/// <exception cref="IOException"> An I/O error occurred. </exception>
1921
/// <exception cref="ArgumentNullException"> Destination is null. </exception>
2022
/// <exception cref="ObjectDisposedException"> Either the current stream or the destination stream is disposed. </exception>
2123
/// <exception cref="NotSupportedException"> The current stream does not support reading, or the destination stream does not support writing. </exception>
22-
public static byte[] ReadToEnd(this Stream stream)
24+
public static byte[] ReadToEnd(this Stream stream, bool leaveOpen = false)
2325
{
2426
using MemoryStream ms = new MemoryStream();
2527
stream.CopyTo(ms);
28+
if (!leaveOpen)
29+
{
30+
stream.Dispose();
31+
}
2632
return ms.ToArray();
2733
}
2834

2935
/// <summary>
3036
/// Asynchronously reads the bytes from the current stream and writes them to the byte array.
3137
/// </summary>
38+
/// <param name="stream"> The stream to read from. </param>
39+
/// <param name="leaveOpen"> If true, the stream will not be disposed after reading. </param>
3240
/// <returns> Received byte array. </returns>
3341
/// <exception cref="ArgumentNullException"> Destination is null. </exception>
3442
/// <exception cref="ObjectDisposedException"> Either the current stream or the destination stream is disposed. </exception>
3543
/// <exception cref="NotSupportedException"> The current stream does not support reading, or the destination stream does not support writing. </exception>
36-
public static async Task<byte[]> ReadToEndAsync(this Stream stream)
44+
public static async Task<byte[]> ReadToEndAsync(this Stream stream, bool leaveOpen = false)
3745
{
3846
using MemoryStream ms = new MemoryStream();
3947
await stream.CopyToAsync(ms);
48+
if (!leaveOpen)
49+
{
50+
await stream.DisposeAsync();
51+
}
4052
return ms.ToArray();
4153
}
4254

0 commit comments

Comments
 (0)