MemoryMappedFile.OpenExisting Method (String)

.NET Framework (current version)

Opens an existing memory-mapped file that has the specified name in system memory.

Namespace:   System.IO.MemoryMappedFiles
Assembly:  System.Core (in System.Core.dll)

public static MemoryMappedFile OpenExisting(
	string mapName


Type: System.String

The name of the memory-mapped file to open.

Return Value

Type: System.IO.MemoryMappedFiles.MemoryMappedFile

A memory-mapped file that has the specified name.

Exception Condition

mapName is an empty string.


mapName is null.


The file specified for mapName does not exist.

The memory-mapped file can be either a persisted memory-mapped file (associated with a file on disk) or non persisted.

Opening a Persisted Memory-Mapped File

The following example opens a memory-mapped file named ImgA that has already been created from a file on disk (as shown in the example for the CreateFromFile(String) method).

using System;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;

class Program
    static void Main(string[] args)
        // Assumes another process has created the memory-mapped file.
        using (var mmf = MemoryMappedFile.OpenExisting("ImgA"))
            using (var accessor = mmf.CreateViewAccessor(4000000, 2000000))
                int colorSize = Marshal.SizeOf(typeof(MyColor));
                MyColor color;

                // Make changes to the view.
                for (long i = 0; i < 1500000; i += colorSize)
                    accessor.Read(i, out color);
                    accessor.Write(i, ref color);

public struct MyColor
    public short Red;
    public short Green;
    public short Blue;
    public short Alpha;

    // Make the view brigher.
    public void Brighten(short value)
        Red = (short)Math.Min(short.MaxValue, (int)Red + value);
        Green = (short)Math.Min(short.MaxValue, (int)Green + value);
        Blue = (short)Math.Min(short.MaxValue, (int)Blue + value);
        Alpha = (short)Math.Min(short.MaxValue, (int)Alpha + value);

Opening a Non-Persisted Memory-Mapped File

The following example opens a memory-mapped file used for inter-process communication. This code example is part of a larger example provided for the CreateNew(String, Int64) method.

.NET Framework
Available since 4.0
Return to top