Advertisement
EddyCZ

Untitled

Oct 6th, 2023
1,156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5.  
  6. class Program
  7. {
  8.     const uint GENERIC_READ = 0x80000000;
  9.     const uint GENERIC_WRITE = 0x40000000;
  10.     const uint OPEN_EXISTING = 3;
  11.     const int INVALID_HANDLE_VALUE = -1;
  12.  
  13.     [DllImport("kernel32.dll", SetLastError = true)]
  14.     public static extern IntPtr CreateFile(
  15.         string lpFileName,
  16.         uint dwDesiredAccess,
  17.         uint dwShareMode,
  18.         IntPtr lpSecurityAttributes,
  19.         uint dwCreationDisposition,
  20.         uint dwFlagsAndAttributes,
  21.         IntPtr hTemplateFile);
  22.  
  23.     [DllImport("kernel32.dll", SetLastError = true)]
  24.     public static extern int WriteFile(
  25.         IntPtr hFile,
  26.         byte[] lpBuffer,
  27.         uint nNumberOfBytesToWrite,
  28.         out uint lpNumberOfBytesWritten,
  29.         IntPtr lpOverlapped);
  30.  
  31.     [DllImport("kernel32.dll", SetLastError = true)]
  32.     public static extern int CloseHandle(IntPtr hObject);
  33.  
  34.     static void Main()
  35.     {
  36.         string pipeName = @"\\.\pipe\MyNamedPipe";
  37.         IntPtr hPipe;
  38.  
  39.         // Connect to the named pipe
  40.         hPipe = CreateFile(pipeName, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
  41.  
  42.         if (hPipe.ToInt32() == INVALID_HANDLE_VALUE)
  43.         {
  44.             Console.WriteLine("Error connecting to named pipe: " + Marshal.GetLastWin32Error());
  45.             return;
  46.         }
  47.  
  48.         Console.WriteLine("Connected to named pipe.");
  49.  
  50.         // Read user input from the console and send it to the named pipe
  51.         while (true)
  52.         {
  53.             Console.Write("Enter text to send to the named pipe (or 'exit' to quit): ");
  54.             string input = Console.ReadLine();
  55.  
  56.             if (input.ToLower() == "exit")
  57.                 break;
  58.  
  59.             byte[] buffer = Encoding.ASCII.GetBytes(input);
  60.             uint bytesWritten;
  61.  
  62.             if (WriteFile(hPipe, buffer, (uint)buffer.Length, out bytesWritten, IntPtr.Zero) == 0)
  63.             {
  64.                 Console.WriteLine("Error writing to named pipe: " + Marshal.GetLastWin32Error());
  65.                 break;
  66.             }
  67.         }
  68.  
  69.         // Close the named pipe and exit
  70.         CloseHandle(hPipe);
  71.         Console.WriteLine("Named pipe closed.");
  72.     }
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement