using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Pipes; using System.Diagnostics; using System.Security.Principal; namespace PipeStream { public delegate void PipeClientError(string message); class PipeClient { public event PipeClientError OnError; private NamedPipeClientStream pipeStream; public void Send(string PipeName, byte[] data, string Host = ".", int TimeOut = 1000, TokenImpersonationLevel level = TokenImpersonationLevel.None) { try { this.pipeStream = new NamedPipeClientStream(Host, PipeName, PipeDirection.Out, PipeOptions.Asynchronous, level); // The connect function will indefinitely wait for the pipe to become available // If that is not acceptable specify a maximum waiting time (in ms) this.pipeStream.Connect(TimeOut); if (this.pipeStream.IsConnected) this.pipeStream.BeginWrite(data, 0, data.Length, AsyncSend, this.pipeStream); } catch (TimeoutException ex) { if (OnError != null) OnError("Connection failed. Reason: " + ex.Message); } } private void AsyncSend(IAsyncResult iar) { try { // Get the pipe NamedPipeClientStream pipeStream = (NamedPipeClientStream)iar.AsyncState; // End the write pipeStream.EndWrite(iar); pipeStream.Flush(); pipeStream.Close(); pipeStream.Dispose(); } catch (Exception ex) { if (OnError != null) OnError("Sending failed. Reason: " + ex.Message); } } public void Close() { if (this.pipeStream != null) { this.pipeStream.Close(); this.pipeStream.Dispose(); } } } }