title: Clearing contents of memory mapped file in C#
body: <p>I am using MemoryMappedFile for communication between 2 programs. Program "A" creates the mmf and reads it's contents on a timer.  Program "B" writes xml data to the mmf on a timer.  I have the memory map working but I run into an issue where the previous iteration of the XML data is longer than the current and old data gets carried over to the next round.</p>
  
  <p>so for simplicity lets say program B writes </p>
  
  <p>aaaa</p>
  
  <p>Program A will read correctly,</p>
  
  <p>Then the next write from program B is: </p>
  
  <p>b</p>
  
  <p>Program A reads</p>
  
  <p>baaa</p>
  
  <p>It seems like there should be some simple way to flush the contents of the memory mapped file but I can't seem to figure it out. It's very possible that I'm totally wrong in the way I'm going about this.</p>
  
  <p>Here's what I'm currently doing.</p>
  
  <p>Program A:</p>
  
  <pre><code>using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("testmap",MemoryMappedFileRights.ReadWrite))
  {
  
      Mutex mutex = Mutex.OpenExisting("testmapmutex");
      mutex.WaitOne();
      string outputtext;
      using (MemoryMappedViewStream stream = mmf.CreateViewStream(0,0))
      {
  
          XmlSerializer deserializer = new XmlSerializer(typeof(MyObject));
          TextReader textReader = new StreamReader(stream);
          outputtext = textReader.ReadToEnd();
          textReader.Close();
  
      }
  
      mutex.ReleaseMutex();
      return outputtext; //ends up in a textbox for debugging
  
  }
  </code></pre>
  
  <p>Program B</p>
  
  <pre><code>using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("testmap", MemoryMappedFileRights.ReadWrite))
  {
  
      Mutex mutex = Mutex.OpenExisting("testmapmutex");
      mutex.WaitOne();
  
      using (MemoryMappedViewStream stream = mmf.CreateViewStream(0, 0))
      {
  
  
          XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
          TextWriter textWriter = new StreamWriter(stream);
          serializer.Serialize(textWriter, myObjectToExport);
          textWriter.Flush();
  
      }
      mutex.ReleaseMutex();
  
  }
  </code></pre>