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.

Advertisement

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 )

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: