13.13. Using Named Pipes to Communicate

Problem

You need a way to use named pipes to communicate with another application across the network.

Solution

Create a P/Invoke wrapper class for the named pipe APIs in Kernel32.dll to allow for managed access, and then create a managed client and managed server class to work with named pipes.

Here are the named pipe interop wrappers in a class called NamedPipeInterop:

namespace NamedPipes { /// <summary> /// Imported namedpipe entry points for p/invoke into native code. /// </summary> [SuppressUnmanagedCodeSecurity] public class NamedPipeInterop { // #defines related to named pipe processing public const uint PIPE_ACCESS_OUTBOUND = 0x00000002; public const uint PIPE_ACCESS_DUPLEX = 0x00000003; public const uint PIPE_ACCESS_INBOUND = 0x00000001; public const uint PIPE_WAIT = 0x00000000; public const uint PIPE_NOWAIT = 0x00000001; public const uint PIPE_READMODE_BYTE = 0x00000000; public const uint PIPE_READMODE_MESSAGE = 0x00000002; public const uint PIPE_TYPE_BYTE = 0x00000000; public const uint PIPE_TYPE_MESSAGE = 0x00000004; public const uint PIPE_CLIENT_END = 0x00000000; public const uint PIPE_SERVER_END = 0x00000001; public const uint PIPE_UNLIMITED_INSTANCES = 255; public const uint NMPWAIT_WAIT_FOREVER = 0xffffffff; public const uint NMPWAIT_NOWAIT = 0x00000001; public const uint NMPWAIT_USE_DEFAULT_WAIT = 0x00000000; public const uint GENERIC_READ = (0x80000000); public const uint GENERIC_WRITE = (0x40000000); public const uint GENERIC_EXECUTE ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.