title: C# Keeping Pipes Open
body: <p>I've Got two Programs (Server / Client)
  I'm trying to setup IPC for them (They both run on the same box)
  Using System.IO.Pipes &amp; Net 3.5</p>
  
  <p>When I call ComOpen, it opens the Pipe correctly, sends the Process ID to the server, but then the Pipe closes and I get an error when it tries to send "Second Write Test"</p>
  
  <p>So Question is.
  How do I keep the Pipe open for the Life of the Program?
  (I use the Process ID on the server to close everything down if the Client crashes)</p>
  
  <pre><code>private static StreamWriter MyWriter;
  private static StreamReader MyReader;
  private static NamedPipeClientStream IPCPipe = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut);
  
  
      public static bool MyWrite(string DataOut)
      {
          bool ValidPipeOut = false;
          if(ValidComPort)
          try
          {
              // Send Data
              using (QstWriter = new StreamWriter(IPCPipe))
              {
                  QstWriter.AutoFlush = true;
                  QstWriter.WriteLine(QstDataOut);
                  QstWriter.Close();
                  QstWriter.Dispose();
              }
              ValidPipeOut = true;
          }
          catch
          {
              ValidPipeOut = false;
          }
          return ValidPipeOut;
      }
  
  
      public static bool ComOpen()
      {
          ValidComPort = true;
  
          try { IPCPipe.Connect(1000); }
          catch (Exception ex)
          {
              string Erroris;
              Erroris = ex.Message;
              if (Erroris == "Already in a connected state.")
              {
                  // We're Already Connected, Ignore this error.
                  ValidComPort = true;
              }
              else
              {
                  ValidComPort = false;
                  MessageBox.Show(Erroris);
              }
          }
          if (ValidComPort)
          {
              string ClientProcessID = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
              MyReader = new StreamReader(IPCPipe);
              ValidComPort = MyWrite(ClientProcessID);
              ValidComPort = MyWrite("Second Write Test");
          }
          return ValidComPort;
      }
  </code></pre>