How would you implement memory-mapped file access using MemoryMappedFile for efficient random access to a very large file?
Short answer
MemoryMappedFile maps a file's contents directly into the process's virtual address space, letting you access arbitrary portions of even a very large file (larger than available RAM) as if it were an in-memory array, with the OS handling paging data in/out transparently — far…
Advertisement
AModel answer
MemoryMappedFile maps a file's contents directly into the process's virtual address space, letting you access arbitrary portions of even a very large file (larger than available RAM) as if it were an in-memory array, with the OS handling paging data in/out transparently — far more efficient than repeated Seek/Read calls for random-access patterns.
using var mmf = MemoryMappedFile.CreateFromFile("huge-file.dat", FileMode.Open);
using var accessor = mmf.CreateViewAccessor(0, 1000);
byte firstByte = accessor.ReadByte(0);
accessor.Write(0, (byte)42); // efficient random access, OS-managed pagingReal-world example
Efficiently performing random-access reads/writes on a multi-gigabyte database or index file without loading it entirely into memory.
Likely follow-ups
- Why is memory-mapped access particularly well-suited for scenarios needing frequent RANDOM (not sequential) access to a huge file?
Related topics