Reading from a memory-mapped file in C# .NET
November 17, 2015 1 Comment
In this post we saw how to write to a memory-mapped file in .NET. We wrote a short string – “Here comes some log message.” – to a 10KB file. Here we’ll quickly look at how to read from the same file by mapping it into memory first.
The way to read from a file is very similar to writing to it. We’ll still need the MemoryMappedFile and MemoryMappedViewAccessor objects:
using (MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateFromFile(@"c:\temp\log.txt", FileMode.OpenOrCreate, "log-map")) { using (MemoryMappedViewAccessor viewAccessor = memoryMappedFile.CreateViewAccessor()) { byte[] bytes = new byte[50]; viewAccessor.ReadArray(0, bytes, 0, bytes.Length); string text = Encoding.UTF8.GetString(bytes).Trim('\0'); } }
So instead of WriteArray we call the ReadArray method. It accepts the position where to start reading the bytes, an array to hold the bytes, and offset and a length. The ‘bytes’ variable could have any length, it will just be padded with zeroes if it’s larger than the source file. In the above case ‘bytes’ will be populated with the first 50 byte values of the source files. If you remember from the post referenced above then you’ll know that the file was padded with a lot of string termination characters. We’ll remove them from the result using the Trim method. The above example returns “Here comes some log message.” in the “text” variable. If I declare ‘bytes’ to have a capacity of 10 elements, then “text” will only be “Here comes”.
Read all posts dedicated to file I/O here.
Hello, I am storing large data into Memory Mapped files. now I want to read it line by line. So please can you guide me that how can it’s possible. “ReadAllLines” is not working for memory mapped file.