Skip to content

Commit 99b9665

Browse files
committed
Fix ReadAsByteArray
1 parent 5c65cb0 commit 99b9665

File tree

2 files changed

+19
-11
lines changed

2 files changed

+19
-11
lines changed

CodeJam.Main/IO/StreamExtensions.cs

+14-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
#if NET45_OR_GREATER || TARGETS_NETSTANDARD || TARGETS_NETCOREAPP // PUBLIC_API_CHANGES
1+

2+
#if NET45_OR_GREATER || TARGETS_NETSTANDARD || TARGETS_NETCOREAPP // PUBLIC_API_CHANGES
23
using System;
34
using System.IO;
45
using System.Text;
@@ -83,9 +84,7 @@ public static string ReadAsString([NotNull] this Stream stream, [CanBeNull] Enco
8384
{
8485
// DO NOT dispose the reader
8586
using (var reader = stream.ToStreamReader(encoding, true))
86-
{
8787
return reader.ReadToEnd();
88-
}
8988
}
9089

9190
/// <summary>
@@ -100,9 +99,7 @@ public static async Task<string> ReadAsStringAsync(
10099
{
101100
// DO NOT dispose the reader
102101
using (var reader = stream.ToStreamReader(encoding, true))
103-
{
104102
return await reader.ReadToEndAsync().ConfigureAwait(false);
105-
}
106103
}
107104

108105
/// <summary>
@@ -112,13 +109,20 @@ public static async Task<string> ReadAsStringAsync(
112109
[NotNull]
113110
public static byte[] ReadAsByteArray([NotNull] this Stream stream)
114111
{
115-
// DO NOT dispose the reader
116-
using (var reader = stream.ToBinaryReader(null, true))
112+
if (stream.CanSeek)
113+
// DO NOT dispose underlying stream
114+
using (var reader = stream.ToBinaryReader(null, true))
115+
{
116+
var readCount = checked((int)(stream.Length - stream.Position));
117+
return reader.ReadBytes(readCount);
118+
}
119+
using (var tempStream = new MemoryStream())
117120
{
118-
var readCount = checked((int)(stream.Length - stream.Position));
119-
return reader.ReadBytes(readCount);
121+
stream.CopyTo(tempStream);
122+
return tempStream.ToArray();
120123
}
121124
}
122125
}
123126
}
124-
#endif
127+
128+
#endif

CodeJam.Main/Readme.txt

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1-
CodeJam 3.3.0 Release Notes
1+
CodeJam 3.3.1 Release Notes
22
---------------------------
33

4+
What's new in 3.3.1
5+
-------------------
6+
* Fix StreamExtensions.ReadAsByteArray (non-seekable stream support)
7+
48
What's new in 3.3.0
59
-------------------
610
* Add more string Invariant and Ordinal methods.

0 commit comments

Comments
 (0)