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.

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


A great site

Elliot Balynn's Blog

A directory of wonderful thoughts

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: