C# MemoryStream is a built-in class in the .NET Framework that allows developers to work with data streams in memory. It provides a way to read and write bytes to an in-memory stream, rather than to a file or network socket.

Using MemoryStream in C#, developers can perform a variety of operations such as buffering data, compressing data, or converting data between different formats. MemoryStream also provides features such as seek and position, which allow developers to read or write data at any point in the stream.

One of the key benefits of using MemoryStream is that it allows for faster data access than traditional file-based operations, which can result in improved performance for applications that handle large amounts of data. Additionally, since data is stored in memory, it is not subject to the same security risks as data stored on disk.

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 by 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 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 the resume column is in binary(max). That will be used for storing any kind of file(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 physical file from the device, and memorystream will use the filestream to read all the bytes and provides an 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.

Convert C# Memorystream to File

Now, while reading the record we need 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 the 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

Overall, C# MemoryStream is a versatile and powerful tool for working with data streams in memory and is widely used in many different types of applications, from web development to desktop applications to mobile app development.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments