Reading and writing a memory-mapped file in .NET Core

Reading and writing a memory-mapped file in .NET Core. Oh, isn't the 2019 console that stays open awesome?

According to Wikipedia, a Memory-mapped file is:

A memory-mapped file is a segment of virtual memory that has been assigned a direct byte-for-byte correlation with some portion of a file or file-like resource

In .NET memory-mapped files can be manipulated using classes in the System.IO.MemoryMappedFiles namespace, which provides classes for creating, reading and writing them. You'd generally use them when you want to access a sub-section of a file, by only loading that part into memory (using a MemoryMappedViewAccessor), or as a method of inter-process communication (IPC).

I needed a simple example recently of reading and writing a memory-mapped file, so thought I'd share it. The code is for a simple console app that runs under .NET Core or .NET Framework which writes some text to a memory-mapped file and then reads it back.

So, without further ado, here it is:

static void Main(string[] args)
{
    var file = CreateFile("Mary had a little lamb, its fleece was white as snow...");

    var contentFromFile = ReadFile(file);

    Console.WriteLine(contentFromFile);
}

private static MemoryMappedFile CreateFile(string content)
{
    var file = MemoryMappedFile.CreateNew("temp.csv", 1048576);

    using (var stream = file.CreateViewStream())
    {
        using (var writer = new StreamWriter(stream))
        {
            writer.WriteLine(content);
        }
    }

    return file;
}

private static string ReadFile(MemoryMappedFile file)
{
    using (var stream = file.CreateViewStream())
    {
        using (var reader = new StreamReader(stream))
        {
            var contentReadFromStream = reader.ReadLine();
            return contentReadFromStream;
        }
    }
}

Breaking it down, the Main method calls CreateFile to create a memory-mapped file and then uses ReadFile to read the content of the memory-mapped file. The CreateFile method creates a new memory-mapped file called temp.csv with a maximum size of 1,048,576 bytes, writes the provided text to it and then returns the file. The ReadFile method is even simpler than that, it uses a StreamReader to extract a line from the memory-mapped file and return it to Main.

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment