title: C# UnauthorizedAccessException when enabling MessageMode for read-only named pipe (NamedPipeClientStream class)
body: <p>There's a problem with the <code>NamedPipeClientStream</code> class in .NET, in that you cannot create an instance of this class with <code>PipeDirection.In</code>, and then successfully change the <code>ReadMode</code> to <code>PipeTransmissionMode.Message</code>. </p>
  
  <p>Attempting to do so will raise an <code>UnauthorizedAccessException</code>. Although pipes would usually be used to communicate between processes, this simple example within a single process shows the problem:</p>
  
  <pre><code>var pipeOut = new NamedPipeServerStream("SomeNamedPipe", 
                                          PipeDirection.Out, 
                                          1, 
                                          PipeTransmissionMode.Message);
  var pipeIn = new NamedPipeClientStream(".", 
                                         "SomeNamedPipe", 
                                         PipeDirection.In);
  pipeIn.Connect();
  pipeIn.ReadMode = PipeTransmissionMode.Message;
  </code></pre>
  
  <p>This code will throw an <code>UnauthorizedAccessException</code> when attempting to set the ReadMode Property. </p>
  
  <hr>
  
  <p>In a search for information on this problem, I found references to it in other places, such as here:</p>
  
  <ul>
  <li><p><a href="http://adventuresindevelopment.blogspot.cl/2008/07/named-pipes-issue-systemunauthorizedacc.html" rel="noreferrer">Named pipes issue: System.UnauthorizedAccessException: Access to the path is denied.</a>  </p></li>
  <li><p><a href="http://www.shujaat.net/2011/01/wpf-messaging-using-windows-pipes.html" rel="noreferrer">WPF - Messaging using Windows Pipes protocol </a>  </p></li>
  <li><a href="https://stackoverflow.com/a/28635708/3418322">PipeTransmissionMode.Message: How do .NET named pipes distinguish between messages?</a></li>
  </ul>
  
  <p>All of these posts mention that this is "weird", "odd", etc, but don't explain "why" it doesn't work, and all give the same workaround, that "for some strange reason" setting the pipe direction to <code>InOut</code> makes it work. </p>
  
  <p>It's true that this does make it work, but it requires fundamentally changing the definition of the pipe, on both ends, to full duplex rather than going in a single direction, which I consider to be a very poor approach, and unless you're able to change both the client and the server, this may not even be possible.</p>
  
  <hr>
  
  <p>My question was, why does enabling message mode on an inbound pipe cause an exception, and is there a better way to address this issue than changing the pipe to bi-directional mode?</p>