Reading from a memory-mapped file in C# .NET

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.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Reading from a memory-mapped file in C# .NET

  1. Hardik Dhankecha says:

    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.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: