Writing to a file using a MemoryMappedFile in C# .NET

You can use memory-mapped files to map a file to a place in memory that multiple processes can access. The necessary objects reside in the System.IO.MemoryMappedFiles namespace.

The following example will create a MemoryMappedFile object using the following ingredients:

  • The file path
  • The file mode which in this example is CreateNew, i.e. a new file will be created if it doesn’t exist
  • A map name that other processes can refer to
  • An initial size of the file. This is mandatory for files that don’t exist otherwise you’ll get an exception. The file will be given this initial size with a lot of string-termination characters. If you try to open the file in a text editor then you may get a warning that the file is full of NULL characters. This depends on the type of editor you’re using

We use the MemoryMappedViewAccessor object extracted from MemoryMappedFile to read and write to the mapped file. You’ll see that writing a string to the file looks somewhat awkward. The reason is that only value types and byte arrays are allowed to be written to a memory mapped file. This conversion is just a trick to save a string.

The first argument to the WriteArray method specifies the location where the string – the byte array – should be inserted.

static void Main(string[] args)
{
	using (MemoryMappedFile memoryMappedFile = 
		MemoryMappedFile.CreateFromFile(@"c:\temp\log.txt", FileMode.CreateNew, "log-map", 10000))
	{
		using (MemoryMappedViewAccessor viewAccessor = memoryMappedFile.CreateViewAccessor())
		{
			byte[] textBytes = Encoding.UTF8.GetBytes("Here comes some log message.");
			viewAccessor.WriteArray(0, textBytes, 0, textBytes.Length);
		}
	}
}

Here’s the file itself after running the method:

Memory-mapped file contents

The file is of size 10KB as specified in the CreateFromFile method.

If you run the above code twice after another then you’ll get an exception saying the source file already exists. Use the “OpenOrCreate” enumeration value of FileMode if it’s OK to work with an existing file. The Append enumeration value is not allowed in conjunction with memory-mapped files. Instead, you’ll need to specify the position of the byte(s) you’d like to write in the file.

Read all posts dedicated to file I/O here.

Advertisements

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:

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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: