There's a problem with the NamedPipeClientStream
class in .NET, in that you cannot create an instance of this class with PipeDirection.In
, and then successfully change the ReadMode
to PipeTransmissionMode.Message
.
Attempting to do so will raise an UnauthorizedAccessException
. Although pipes would usually be used to communicate between processes, this simple example within a single process shows the problem:
var pipeOut = new NamedPipeServerStream("SomeNamedPipe",
PipeDirection.Out,
1,
PipeTransmissionMode.Message);
var pipeIn = new NamedPipeClientStream(".",
"SomeNamedPipe",
PipeDirection.In);
pipeIn.Connect();
pipeIn.ReadMode = PipeTransmissionMode.Message;
This code will throw an UnauthorizedAccessException
when attempting to set the ReadMode Property.
In a search for information on this problem, I found references to it in other places, such as here:
Named pipes issue: System.UnauthorizedAccessException: Access to the path is denied.
- PipeTransmissionMode.Message: How do .NET named pipes distinguish between messages?
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 InOut
makes it work.
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.
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?
PipeDirection
enum is named exactly backwards. You write to the input end of a unidirectional pipe, the data goes down the pipe to the other process, and then can be read from the output end. ButPipeDirection.In
means readable (the output end of the pipe). – Whitefaced