Working With Streams In C#

Code Snippets Working With Streams In C#
Share:

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);
            }
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger