How to use MemoryStream in C#

MemoryStream provides a sophisticated way to work with in-memory data streams in C#. It enables you to manipulate data as if it were saved in a file, giving you flexibility and efficiency in a variety of situations. In this post, we’ll go through the ins and outs of MemoryStream in C#, including its features, benefits, and best practices.

Install Required Software

  • NET Core SDK from here
  • Visual Studio or Visual Studio Code from here

What is MemoryStream?

MemoryStream is a C# class that extends the Stream class. It represents a stream that stores its data in memory rather than a file. It provides methods for reading from and writing to the underlying byte array, making it a useful tool for handling data in memory.

Writing from a File

To save the contents of a MemoryStream to a file, use the Write method with a FileStream representing the target file. Here’s an example.

 byte[] buffer = System.Text.Encoding.ASCII.GetBytes("Hello World!");
                using (FileStream fileStream = File.Create("Result.txt"))
                {
                 
                    var stream = new MemoryStream(buffer);
                    fileStream.Write(buffer, 0, buffer.Length);
                    fileStream.Flush();
                    fileStream.Close();
                    
                    
                }    

Reading from a File

Similarly, the ReadFrom method can be used to read the contents of a file into a MemoryStream. This function accepts a FileStream as the source file. Here’s an example.

          
byte[] filecontents = File.ReadAllBytes("document.txt");
            using (var stream = new MemoryStream(filecontents))
            {
                using(TextReader readline= new StreamReader(stream))
                {
                    string ln;
                    while((ln= readline.ReadLine()) != null)
                    {
                        Console.WriteLine(ln);
                    }

                }
            } 

Using Files and MemoryStream

You may conveniently read from and write to files using well-known stream operations when utilizing MemoryStream in conjunction with files.

FileStream vs. MemoryStream

Although both MemoryStream and FileStream are helpful for working with data streams, their traits and use cases vary. While FileStream interacts with data that is kept on a disc, MemoryStream runs solely in memory. The decision between them is based on the particular needs of your application.

Advantages of MemoryStream

  • There are various advantages to using MemoryStream in C#, including:
  • Efficiency: Working with data in memory moves more quickly than doing I/O operations on a disc.
  • Flexibility: MemoryStream offers well-known stream-based operations and lets you treat data as if it were stored in a file.
  • Working with a MemoryStream is simple.
  • Convenience: Working with a MemoryStream is simple and doesn’t involve handling physical files.

Full Source Code

 
namespace MemoryStream_Csharp
{
    internal class Program
    {
        static void Main(string[] args) 
        {
            byte[] filecontents = File.ReadAllBytes("document.txt");
            using (var stream = new MemoryStream(filecontents))
            {
                using(TextReader readline= new StreamReader(stream))
                {
                    string ln;
                    while((ln= readline.ReadLine()) != null)
                    {
                        Console.WriteLine(ln);
                    }

                }
            }

            byte[] buffer = System.Text.Encoding.ASCII.GetBytes("Hello World!");
                using (FileStream fileStream = File.Create("Result.txt"))
                {
                 
                    var stream = new MemoryStream(buffer);
                    fileStream.Write(buffer, 0, buffer.Length);
                    fileStream.Flush();
                    fileStream.Close(); 
                }         
        } 
    }
}

More Related Post Remove Duplicates from an Array in C#

Conclusion
In this post, we looked at MemoryStream’s use in C#. We covered creating a MemoryStream, writing to it, and reading data from it, as well as using it in combination with files. Additionally, we outlined MemoryStream’s advantages and disadvantages and offered recommended practices for effective utilization.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments