DEV Community

Volkan Alkılıç
Volkan Alkılıç

Posted on • Edited on

Using Named Pipes in C# for Interprocess Communication

Named pipes are a type of interprocess communication (IPC) mechanism that allow data to be exchanged between two or more processes on a computer. They are called "named" pipes because they are identified by a unique name, rather than by a file descriptor like other types of pipes in Unix-like systems.

Named pipes are useful for a variety of purposes, including:

  • Enabling processes that run on different computers to communicate with each other over a network
  • Allowing processes to communicate with each other even if they don't have permission to access each other's memory or files
  • Allowing multiple processes to read and write to the same pipe concurrently
  • In C#, named pipes can be created and used through the System.IO.Pipes namespace. To create a named pipe, you can use the NamedPipeServerStream or NamedPipeClientStream class, depending on whether you want to create a server or client pipe.

Here is an example of how to create a named pipe server in C#:

using (var server = new NamedPipeServerStream("my_pipe_name"))
{
    Console.WriteLine("Waiting for client connection...");
    server.WaitForConnection();
    Console.WriteLine("Client connected.");

    // Read and write data through the pipe
}

Enter fullscreen mode Exit fullscreen mode

And here is an example of how to create a named pipe client in C#:

using (var client = new NamedPipeClientStream(".", "my_pipe_name", PipeDirection.InOut))
{
    Console.WriteLine("Connecting to server...");
    client.Connect();
    Console.WriteLine("Connected to server.");

    // Read and write data through the pipe
}

Enter fullscreen mode Exit fullscreen mode

Once a named pipe has been created, you can use the Read() and Write() methods of the NamedPipeServerStream or NamedPipeClientStream class to read and write data to the pipe.

Join Me

Follow me on Twitter and Linkedin for more content.

Top comments (4)

Collapse
 
pingkunga profile image
Chatri Ngambenchawong

pipe is very powerful. In my work I apply pipe to communicate between VB6 > .NET application

Collapse
 
pefthymiou profile image
Panagiotis Efthymiou

Would it be possible to provide a simple example of that?

Collapse
 
pingkunga profile image
Chatri Ngambenchawong

I write blog about this here >> naiwaen.debuggingsoft.com/2022/03/... (In Thai), you see source code and git repo.

Thread Thread
 
pefthymiou profile image
Panagiotis Efthymiou

Thanks! I'll have a look.