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("testdata.data" ,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"); writer.Flush(); Console.ReadLine();
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()); reader.Close(); Console.ReadLine();