Convert Stream To Byte Array In C#

Sameer Saini March 24, 2022
Convert Stream To Byte Array In C#

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 ToArrayAsync(this Stream stream) { var memoryStream = new MemoryStream(); await memoryStream.CopyToAsync(stream); return memoryStream.ToArray(); } } // To Call the above method // Incoming File Stream var fileStream = File.Open("C:/somefile.txt", FileMode.Open); // Convert Stream To Byte Array Asynchronously byte[] bytes = await fileStream.ToArrayAsync();

 

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#.