简体   繁体   中英

Handling Memory mapped File in C# directly from the memory

Is it possible to open memory mapped file in C# directly just like opening files directly in windows, say for example, I'm creating memory mapped file. through following code.

using System;
using System.IO.MemoryMappedFiles;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test.txt", 5);
            MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
            var arun = new[] {(byte)'a', (byte)'r', (byte)'u', (byte)'n'};
            for (int i = 0; i < arun.Length; i++)
                accessor.Write(i, arun[i]);
            Console.WriteLine("Memory-mapped file created!");
            Console.ReadLine(); // pause till enter key is pressed
            accessor.Dispose();
            mmf.Dispose();
        }
    }
}

I need to open the file directly. Is it possible like opening file through

Process.start("test.txt");

from another process instead of reading values by the code .

 MemoryMappedFile mmf1 = MemoryMappedFile.OpenExisting("test.txt");
 MemoryMappedViewAccessor accessor1 = mmf1.CreateViewAccessor();
 var  value = accessor1.ReadByte(4);    

If it possible to open memory mapped file directly? Please let me know.

Starting with the .NET Framework version 4, you can use managed code to access memory-mapped files in the same way that native Windows functions access memory-mapped files, as described in Managing Memory-Mapped Files in Win32 in the MSDN Library.

The MemoryMappedFile.CreateNew method creates a file mapping object that is not associated with a file on disk. So no, you can't open the file directly, because there isn't one. (Such file mapping objects are backed by the system paging file, as described here .)

You can use the MemoryMappedFile.CreateFromFile method instead if you want to associate the file mapping object with an actual file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM