Reading and writing a memory-mapped file in .NET Core
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.