Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Text;
- class Program
- {
- const uint GENERIC_READ = 0x80000000;
- const uint GENERIC_WRITE = 0x40000000;
- const uint OPEN_EXISTING = 3;
- const int INVALID_HANDLE_VALUE = -1;
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern IntPtr CreateFile(
- string lpFileName,
- uint dwDesiredAccess,
- uint dwShareMode,
- IntPtr lpSecurityAttributes,
- uint dwCreationDisposition,
- uint dwFlagsAndAttributes,
- IntPtr hTemplateFile);
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern int WriteFile(
- IntPtr hFile,
- byte[] lpBuffer,
- uint nNumberOfBytesToWrite,
- out uint lpNumberOfBytesWritten,
- IntPtr lpOverlapped);
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern int CloseHandle(IntPtr hObject);
- static void Main()
- {
- string pipeName = @"\\.\pipe\MyNamedPipe";
- IntPtr hPipe;
- // Connect to the named pipe
- hPipe = CreateFile(pipeName, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
- if (hPipe.ToInt32() == INVALID_HANDLE_VALUE)
- {
- Console.WriteLine("Error connecting to named pipe: " + Marshal.GetLastWin32Error());
- return;
- }
- Console.WriteLine("Connected to named pipe.");
- // Read user input from the console and send it to the named pipe
- while (true)
- {
- Console.Write("Enter text to send to the named pipe (or 'exit' to quit): ");
- string input = Console.ReadLine();
- if (input.ToLower() == "exit")
- break;
- byte[] buffer = Encoding.ASCII.GetBytes(input);
- uint bytesWritten;
- if (WriteFile(hPipe, buffer, (uint)buffer.Length, out bytesWritten, IntPtr.Zero) == 0)
- {
- Console.WriteLine("Error writing to named pipe: " + Marshal.GetLastWin32Error());
- break;
- }
- }
- // Close the named pipe and exit
- CloseHandle(hPipe);
- Console.WriteLine("Named pipe closed.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement