Home > Backend Development > C++ > How to Convert a Byte Array to a Stream in C#?

How to Convert a Byte Array to a Stream in C#?

Susan Sarandon
Release: 2024-12-28 07:44:52
Original
861 people have browsed it

How to Convert a Byte Array to a Stream in C#?

Converting System.Byte byte[] to System.IO.Stream in C#

In C#, the process of converting a byte array into a stream object is relatively straightforward. This can be achieved through the use of the MemoryStream class, which provides a convenient way to create a stream that is backed by an in-memory byte array.

Solution:

The simplest approach to convert a byte array to a stream is to utilize the MemoryStream constructor:

Stream stream = new MemoryStream(byteArray);
Copy after login

Where byteArray is the byte array you wish to convert. The MemoryStream created through this method allows you to access and manipulate the data in the byte array as if it were stored in a file. This enables various operations such as reading, writing, and seeking within the stream.

For instance, suppose you have a byte array named "bytes" that contains binary data. You can convert it to a stream like this:

byte[] bytes = { 0x41, 0x42, 0x43, 0x44 };
Stream stream = new MemoryStream(bytes);
Copy after login

Now, stream is an in-memory representation of your byte array, providing you with the ability to perform stream-based operations on the data.

The above is the detailed content of How to Convert a Byte Array to a Stream in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template