Convert Byte To Stream In C#

Sameer Saini March 06, 2023
Convert Byte To Stream In C#

To convert a byte array to a stream in C#, you can use the MemoryStream class, which provides a stream backed by an in-memory buffer.

Example

Here's an example:

byte[] bytes = new byte[] { 65, 66, 67 };

// Create a MemoryStream from the byte array
MemoryStream stream = new MemoryStream(bytes);

// Use the stream for reading or writing
// For example, you can read the contents of the stream as a string
string contents = new StreamReader(stream).ReadToEnd();

In this example, we create a byte array with the values 65, 66, and 67, which correspond to the ASCII characters 'A', 'B', and 'C'. We then create a MemoryStream object from the byte array by passing it to the MemoryStream constructor.

Once we have the stream, we can use it for reading or writing data. In this example, we create a StreamReader object from the stream and use it to read the contents of the stream as a string.

Conclusion

Using the MemoryStream class in C#, you can easily convert a byte array to a stream. This can be useful when working with APIs or libraries that require a stream as input, or when you need to manipulate the data in a byte array using stream-based operations.