Avatar ·

How to create a byte array from a Stream in C#? Complete guide

Hello everyone! I'm new to C# and working on an application that downloads files from the internet. I need to read all data from NetworkStream or FileStream into a byte[] array. The problem is that I don't know the stream size in advance. I tried using the Length property, but for many streams it throws a NotSupportedException.\n\nHere's my current code that doesn't work:\n\n
// Trying to read a stream into a byte array\nbyte[] buffer = new byte[stream.Length]; // Error: 'Stream' does not support seeking\nstream.Read(buffer, 0, buffer.Length);\n
\n\nThis error occurs when I work with network streams (NetworkStream) or streams from HTTP responses. I understand that I need to read data in chunks, but I don't know how to properly organize the loop. I saw something about Memory