读,写,追加,删除内存映射文件

时间:2012-03-01 05:42:39

标签: c# memory-mapped-files

在我的Windows应用程序中,我想使用内存映射文件。网上有各种文章/博客,它们有足够的信息来创建内存映射文件。我正在创建2个内存映射文件,现在我想对这些文件执行一些操作,比如阅读其内容,在其中添加一些内容,从中删除一些内容。所有这些都可能有更多关于网络的信息,但不幸的是我找不到任何东西。 下面是我用来编写内存映射文件的函数。

 // Stores the path to the selected folder in the memory mapped file
        public void CreateMMFFile(string folderName, MemoryMappedFile mmf, string fileName)
        {
            // Lock
            bool mutexCreated;
            Mutex mutex = new Mutex(true, fileName, out mutexCreated);
            try
            {
                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    using (StreamWriter writer = new StreamWriter(stream, System.Text.Encoding.Unicode))
                    {
                        try
                        {
                            string[] files = System.IO.Directory.GetFiles(folderName, "*.*", System.IO.SearchOption.AllDirectories);
                            foreach (string str in files)
                            {
                                writer.WriteLine(str);
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Unable to write string. " + ex);
                        }
                        finally
                        {
                            mutex.ReleaseMutex();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to monitor memory file. " + ex);
            }
        }

如果有人可以帮助我,那将非常感激。

2 个答案:

答案 0 :(得分:1)

我认为你要找的班级是MemoryMappedViewAccessor。它提供了读取和写入内存映射文件的方法。删除只不过是一系列经过精心策划的写作。

可以使用CreateViewAccessor方法从MemoryMappedFile班级创建。

答案 1 :(得分:0)

在这段代码中,我做了类似于你想要实现的东西。我每秒都写MMF,你可以让其他进程读取该文件中的内容:

var data = new SharedData
{
    Id = 1,
    Value = 0
};

var mutex = new Mutex(false, "MmfMutex");

using (var mmf = MemoryMappedFile.CreateOrOpen("MyMMF", Marshal.SizeOf(data)))
{
     using (var accessor = mmf.CreateViewAccessor())
     {
          while (true)
          {
              mutex.WaitOne();
              accessor.Write(0, ref data);
              mutex.ReleaseMutex();

              Console.WriteLine($"Updated Value to: {data.Value}");
              data.Value++;
              Thread.Sleep(1000);
           }
     }
}

查看this article,了解如何使用MMF在进程之间共享数据。