2012-03-01 68 views
3

在我的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); 
      } 
     } 

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

+0

[MSDN文档示例](http://msdn.microsoft.com/en-us/library/dd997372.aspx)的哪个部分是您特别有问题的理解? – 2012-03-01 05:59:54

+0

我没有这样说过。下投票?原因?? – 2012-03-01 06:07:02

+0

文档(特别是文档中的示例)包含从MMF读取和写入的例子,所以我很困惑;你在问什么? – 2012-03-01 06:08:49

回答

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

看看到this article,了解你怎么可以共享使用MMF的进程之间的数据。

+0

尽管这个链接可能回答这个问题,但最好是包括答案的基本部分,并提供参考链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/18517303) – Jobin 2018-01-15 04:56:50