What is a Stream in C#?
A stream is an abstract class in C# that represents a sequence of bytes that can be read or written to. Streams are often used for I/O operations such as reading or writing files, sending or receiving data over a network, or working with other types of input or output data.
In this blog post, we will see how we can convert a stream to byte array in C# using the .ToArray() method available on the MemoryStream class.
We will use the .ToArray() method available on the MemoryStream class and convert stream to byte array.
Convert Stream To Byte Array In C# Using .ToArray() Method
// Incoming File Stream var fileStream = File.Open("C:/somefile.txt", FileMode.Open); // Create a new instance of memorystream var memoryStream = new MemoryStream(); // Use the .CopyTo() method and write current filestream to memory stream fileStream.CopyTo(memoryStream); // Convert Stream To Array byte byteArray = memoryStream.ToArray();
In the above code example, we can see that we first get an incoming stream that we want to convert to a byte array.
In this example, the stream is a FileStream and we will convert a FileStream to Byte Array in C#.
First, we create a new MemoryStream instance using the new keyword.
Then using the .CopyTo method, we write the filestream to memorystream.
After that, using the .ToArray() method available to us on the MemoryStream class instance, we will use that to convert the stream to a byte array in C#.
Generic Method - C# Stream To Byte Array - Convert Stream To Byte Array Asynchronously
Now, we will use the above information and create a generic method that you can just copy paste and use it in your solution.
public static class StreamExtensions
public static async Task
In the above generic method, we made use of the .CopyToAsync() method available on the MemoryStream class and created a generic extension method that converts a stream to byte array in C#.