读取、写入、追加、删除内存映射文件

4
在我的Windows应用程序中,我想使用内存映射文件。网络上有各种文章/博客提供了足够的信息来创建内存映射文件。我正在创建两个内存映射文件,现在我想对这些文件执行一些操作,例如读取它的内容,追加一些内容到其中,从其中删除一些内容。可能有更多关于所有这些的信息在网络上,但不幸的是我找不到任何东西。 以下是我正在使用的编写内存映射文件的函数。
 // 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);
            }
        }

如果有人能帮忙,那将不胜感激。

我没有说过那样的话。踩票??原因是什么? - Deepak Kumar
文档(特别是文档中的示例)包含了从/向MMF读写的示例,所以我有点困惑,你在问什么? - M.Babcock
抱歉,我没看到那个。 - Deepak Kumar
我没有。实际上,我很喜欢你的问题。 - M.Babcock
让我们在聊天中继续这个讨论。点击此处进入聊天室 - Deepak Kumar
显示剩余2条评论
2个回答

1

我认为你要找的类是 MemoryMappedViewAccessor。它提供了读写内存映射文件的方法。删除只是一系列精心编排的写操作。

可以使用 CreateViewAccessor 方法从你的 MemoryMappedFile 类创建它。


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);
           }
     }
}

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接