About
In this code snippet, we will learn about streams in C#.
Streams provide a generic view of a sequence of bytes. The Stream class is an abstract class that defines all the necessary things for any inheriting stream to implement such as Read(), Write(), Seek() and Flush() methods.
Some of the commonly used streams present in .NET are FilesStream, MemoryStream, BufferedStream. Usually, they are used when dealing with different kinds of I/O such as files, network and other communications.
I already made a few posts where you can see streams being used in more practical examples such as reading and writing files, uploading and downloading files in Blazor or uploading and downloading files from Azure Blob storage.
Note: Streams can be synchronous or asynchronous and should be disposed of manually or used with the using keyword.
Let’s have a look at the code below to see how to utilize streams.
Code:
namespace csStreams { internal class Program { static void Main(string[] args) { using (MemoryStream ms = new MemoryStream()) { //Write some text to a byte array. byte[] text = System.Text.Encoding.UTF8.GetBytes("Hello World."); //Then write the byte array to the memory stream. ms.Write(text, 0, text.Length); //Rewind the stream to the beginning. ms.Seek(0, SeekOrigin.Begin); //Read the stream into another byte array. byte[] buffer = new byte[ms.Length]; ms.Read(buffer, 0, buffer.Length); //Convert the byte array back to a string. string textResult = System.Text.Encoding.UTF8.GetString(buffer); Console.WriteLine(textResult); } } } }