This C# code creates a 1000 byte memory mapped file and writes 08112003 at position 500

159 Views Asked by At
using (MemoryMappedFile mmFile = MemoryMappedFile.CreateNew("Raise", 1000))
{
    using (MemoryMappedViewAccessor accessor = mmFile.CreateViewAccessor())
    {
        accessor.Write(500, 11082003);
        Console.WriteLine("Memory-mapped file created!");
    }
}

using (MemoryMappedFile mmFile = MemoryMappedFile.OpenExisting("Raise"))
{
    using (MemoryMappedViewAccessor accessor = mmFile.CreateViewAccessor())
    {
        int value = accessor.ReadInt32(500);
        Console.WriteLine("The answer is : {0}", value);
    }
}

But, every time I try to read my integer value of 11082003, this is what I get, System.IO.FileNotFoundException: 'Unable to find the specified file.'. What might be the issue?

1

There are 1 best solutions below

0
Jon Skeet On

You're disposing of the resource you've written to, which is only in memory. From the documentation for MemoryMappedFile.CreateNew:

Use this method to create a memory-mapped file that is not persisted (that is, not associated with a file on disk), which you can use to share data between processes.

So when you dispose of that, the name isn't valid any more.

If you change your code to avoid disposing of the "creating" part until the end, it works:

using System.IO.MemoryMappedFiles;

using (MemoryMappedFile mmFile1 = MemoryMappedFile.CreateNew("Raise", 1000))
{
    using (MemoryMappedViewAccessor accessor = mmFile1.CreateViewAccessor())
    {
        accessor.Write(500, 11082003);
        Console.WriteLine("Memory-mapped file created!");
    }


    using (MemoryMappedFile mmFile2 = MemoryMappedFile.OpenExisting("Raise"))
    {
        using (MemoryMappedViewAccessor accessor = mmFile2.CreateViewAccessor())
        {
            int value = accessor.ReadInt32(500);
            Console.WriteLine("The answer is : {0}", value);
        }
    }
}

Alternatively, to use an actual file, you can use CreateFromFile both times:

using System.IO.MemoryMappedFiles;

using (MemoryMappedFile mmFile = MemoryMappedFile.CreateFromFile("Raise", FileMode.Create, null, 1000))
{
    using (MemoryMappedViewAccessor accessor = mmFile.CreateViewAccessor())
    {
        accessor.Write(500, 11082003);
        Console.WriteLine("Memory-mapped file created!");
    }
}

using (MemoryMappedFile mmFile = MemoryMappedFile.CreateFromFile("Raise"))
{
    using (MemoryMappedViewAccessor accessor = mmFile.CreateViewAccessor())
    {
        int value = accessor.ReadInt32(500);
        Console.WriteLine("The answer is : {0}", value);
    }
}