Software Architecture – C# – 4.0 – New Feature – Memory Mapped File

While exploring new features of C# 4.0 , i came across with concept of memory mapped file.

According Wiki , memory mapped file can be defined as:

A memory-mapped file is a segment of virtual memory which has been assigned a direct byte-for-byte correlation with some portion of a file or file-like resource. This resource is typically a file that is physically present on-disk, but can also be a device, shared memory object, or other resource that the operating system can reference through a file descriptor.

In C# 4.0, Microsoft has introduced a new namespace “System.IO.MemoryMappedFiles” for manipulating memory mapped file.

CreateViewStream method of MemoryMappedFiles is used to create a stream which is mapped to memory mapped file.

Data can be written to memory mapped file as:

MemoryMappedFile mmFile = MemoryMappedFile.CreateNew("" ,int.MaxValue,MemoryMappedFileAccess.ReadWriteExecute);
var wStream = mmFile.CreateViewStream(0,3000);
BinaryWriter writer = new BinaryWriter(wStream);
writer.Write("Very Very Very Very Very huge volume of data ..............");
Console.WriteLine("Data has been written to Memory Mapped file");

Data can be read from memory mapped file as:

var rStream = mmFile.CreateViewStream(0, 3000);
BinaryReader reader = new BinaryReader(rStream);            
Console.WriteLine("Data read from Memory Mapped file as: " + reader.ReadString());

Enjoy Coding….


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: