Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NamedPipes
internal class Program
// usage: dotnet run -c Release server $pipeName
// dotnet run -c Release client $pipeName
static async Task Main(string[] args)
string pipeName = args[1];
CancellationTokenSource timeout = new (TimeSpan.FromSeconds(10));
if (args[0] == "server")
using NamedPipeServerStream server = new (pipeName, PipeDirection.In, maxNumberOfServerInstances: 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
Console.WriteLine("Server waiting for client to connect");
await server.WaitForConnectionAsync(timeout.Token);
Console.WriteLine("Server established a connection!");
using StreamReader streamReader = new StreamReader(server, Encoding.UTF8);
string line = null;
while ((line = await streamReader.ReadLineAsync()) != null)
using NamedPipeClientStream client = new (".", pipeName, PipeDirection.Out, PipeOptions.Asynchronous);
Console.WriteLine("Client waiting to connect to a server");
await client.ConnectAsync(timeout.Token);
Console.WriteLine("Client connected!");
await client.WriteAsync(Encoding.UTF8.GetBytes($"Line 1 {Environment.NewLine}"), timeout.Token);
await client.WriteAsync(Encoding.UTF8.GetBytes($"Line 2"), timeout.Token);
await client.WriteAsync(Encoding.UTF8.GetBytes($" still line 2 {Environment.NewLine}"), timeout.Token);
await client.WriteAsync(Encoding.UTF8.GetBytes($"Line 3 {Environment.NewLine}"), timeout.Token);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment