Before reading or writing to any memory mapped file (MMF), we map a view of the file. This returns a Stream, giving easy access to the memory as we can use the Stream functions such as Seek, StreamReader and StreamWriter to read/write to the MMF.
An MMF is a stream of bytes divided into a group of records. Each record is defined with a maximum record size. The size of the MMF is simply the number of records * each record size. In this example, to map a view to MMF with 20 records with each record being 100 bytes, we define a constant MAX_BYTES as 2000 (20 records * 100 bytes)
Stream view = map.MapView(MapAccess.FileMapWrite, 0, MAX_BYTES)
To read or write to a particular record, we “seek” to the starting byte using this formula: starting record number * record size. For example, if record 5 is to be read (using the example from above), we use the stream’s read method to start at the first byte of record 5 and read the next 100 bytes:
byte bytes = new byte[MAX_REC_SIZE];
int nBytes = view.Read(bytes, 5*MAX_REC_SIZE, MAX_REC_SIZE);
Similarly, writing to an MMF is using the stream’s Write method. In this example, rather than reading the 5th record, we will write to the 5th record:
view.Write(bytes, 5*MAX_REC_SIZE, MAX_REC_SIZE);