Before we start on the MemoryStrream in C#. First, let me give some highlights on the Stream, What it is and why to use that.

Stream is an abstract class provided under the System.IO namespace and has methods to perform the IO(Input/Output) reading and writing operations. Transferring the bytes from one source to another.

What is C# MemoryStream?

As the name suggests MemoryStream in C# is used for storing the stream in the system memory or RAM. It is inherited from the base class Stream like FileStream which is used for reading the content of physical files.

Use cases of MemoryStream in C#

One of the fastest ways of accessing the data in the application is storing things in the memory of the system.

With MemoryStream, you can act upon the byte[] stored in memory rather than a file or other resource. Use a byte[] because it is a fixed-sized object, making memory allocation and cleanup easier.

  • When you want the bytes as the output of the stream. You can go for MemoryStream.
  • It can be used for increasing the performance by storing the backup data in the memory instead of directly reading and writing into the file or network.

Save Images into Database Using MemoryStream in C#

This is one of the use cases of using the memorystream in C#. As part of this demo project, we will be reading and writing pdf files into the MySQL database.

Database table for storing the image along with some other properties. As you see in the image, Datatype for resume column in binary(max). That will be used for storing any kind of fines(image, pdf, or ms word) file.

C# MemoryStream
Database Table for Storing binary data
using System;
using System.IO;
using System.Net.Sockets;
using Microsoft.EntityFrameworkCore;

namespace Demo.App
{
    class Program
    {
        static void Main(string[] args)
        {
            using var fs = new FileStream(@"C:\Users\DKU127\Desktop\Reusme.pdf", FileMode.Open);
            using var ms = new MemoryStream();
            fs.CopyTo(ms);
            SaveEmployeeDetails("Deependra", ms.ToArray());
            Console.ReadKey();
            
        }

        private static void SaveEmployeeDetails(string EmployeeName, byte[] bytes)
        {
            var employee = new Employee()
            {
                Name = EmployeeName,
                Resume = bytes
            };
            var context = new EmployeeContext();
            context.Employees.Add(employee);
            context.SaveChanges();
        }

    }
}

As we see in the above piece of code. FileStream will help us to read the pythical file from the device, and memorystream will use the filestream to read all the bytes and provides and array of bytes.

C# MemoryStream
Database with binary column

We can validate the saved entry by navigating to the SQL server and querying the [Employees] table.

So we are done with writing the file into the SQL server database. Now, while reading the record we needs to again convert back the binary to the original file.

using System;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using Microsoft.EntityFrameworkCore;

namespace Demo.App
{
    class Program
    {
        static void Main(string[] args)
        {
            var employee = GetEmployeeDetails("Deependra");
            var resume = employee.Resume;
            File.WriteAllBytes("DownloadedResume.pdf", resume);

        }

        private static Employee GetEmployeeDetails(string name)
        {
            var context = new EmployeeContext();
            return context.Employees.FirstOrDefault(x => x.Name.ToLower() == name.ToLower());
        }

    }
}

Above lines of code can be used for reading the stored bytes from database and converting the bytes again to the pdf file.

Convert Stream to Byte Array in C#

MemoryStream can be used for transforming the data between bytes array to stream and stream to bytes array in C#.

using var fileStream = new FileStream(@"C:\DK\test.text.json", FileMode.Open);
//Read the file using filstream
using var memoryStream = new MemoryStream();
fileStream.CopyTo(memoryStream);
//Copy file stream into the MemoryStream
memoryStream.ToArray();
//Ge the array of bytes from the MemoryStream

Convert Bytes Array to Stream in C#

MemoryStream in C# can be also used for converting the array of bytes to the stream.

//Note : this code is using the C# version 8.0
var fileContentsAllBytes = File.ReadAllBytes(@"C:\DK\test.text.json");
using var memoryStream = new MemoryStream(fileContentsAllBytes);
using TextReader textReader = new StreamReader(memoryStream);
while (textReader.ReadLine() is { } line)
    Console.WriteLine(line);

Convert C# MemoryStream to String

    var fs = new FileStream(@"C:\Users\DKU\Desktop\Reusme.pdf", FileMode.Open);
            var ms = new MemoryStream();
            fs.CopyTo(ms);
            var stringFromMs = System.Text.Encoding.UTF8.GetString(ms.ToArray());
            Console.Write(stringFromMs);

Above lines of code can be used for converting the memorystream to string using the UTF8 encoding.

Conclusion

In this post, We have seen the usage of memorystream class in C#. Memorystream can be used for copying another stream object and also reading the stream as byte array.

79 / 100

Comments

No comments yet. Why don’t you start the discussion?