2012-03-01 135 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