Avatar ·

How to create a byte array (byte[]) from a Stream in C#?

Hello everyone! I'm a beginner C# developer and I have a problem. I need to read all data from a Stream into a byte array (byte[]). The stream can come from different sources: file, network request, MemoryStream, etc. Here's an example of the code I'm trying to write: ```csharp public byte[] ReadStream(Stream stream) { // I know that Stream has Length, but it's not always available. // How to correctly read all bytes? byte[] buffer = new byte[stream.Length]; // Error "Stream does not support seeking" stream.Read(buffer, 0, (int)stream.Length); return buffer; } ``` The problem is that `stream.Length` can throw a `NotSupportedException` if the stream does not support seeking. For example, when working with `NetworkStream` or `GZipStr