[英]Creating a Windows named pipe with a C# FileStream
在FileStream
類的文檔中, Remarks
部分說:
使用 FileStream 類讀取、寫入、打開和關閉文件系統上的文件,以及操作其他與文件相關的操作系統句柄,包括管道、標准輸入和標准輸出。
我知道 System.IO.Pipes 用於在 Windows 中從管道創建、讀取和寫入,但由於我目前正在處理的項目的限制,我無法訪問該包。 似乎 FileStreams 可以與管道進行交互,但我似乎找不到任何有關如何執行此操作的示例。
如何直接使用 FileStream 在 Windows 中通過命名管道執行基本 I/O?
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace Test
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateNamedPipe(string lpName, uint dwOpenMode,
uint dwPipeMode, uint nMaxInstances, uint nOutBufferSize, uint nInBufferSize,
uint nDefaultTimeOut, IntPtr lpSecurityAttributes);
static uint PIPE_ACCESS_DUPLEX = 0x00000003;
static uint PIPE_ACCESS_INBOUND = 0x00000001;
static uint PIPE_ACCESS_OUTBOUND = 0x00000002;
static uint FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
static uint FILE_FLAG_WRITE_THROUGH = 0x80000000;
static uint FILE_FLAG_OVERLAPPED = 0x40000000;
static uint WRITE_DAC = 0x00040000;
static uint WRITE_OWNER = 0x00080000;
static uint ACCESS_SYSTEM_SECURITY = 0x01000000;
//One of the following type modes can be specified. The same type mode must be specified for each instance of the pipe.
static uint PIPE_TYPE_BYTE = 0x00000000;
static uint PIPE_TYPE_MESSAGE = 0x00000004;
//One of the following read modes can be specified. Different instances of the same pipe can specify different read modes
static uint PIPE_READMODE_BYTE = 0x00000000;
static uint PIPE_READMODE_MESSAGE = 0x00000002;
//One of the following wait modes can be specified. Different instances of the same pipe can specify different wait modes.
static uint PIPE_WAIT = 0x00000000;
static uint PIPE_NOWAIT = 0x00000001;
//One of the following remote-client modes can be specified. Different instances of the same pipe can specify different remote-client modes.
static uint PIPE_ACCEPT_REMOTE_CLIENTS = 0x00000000;
static uint PIPE_REJECT_REMOTE_CLIENTS = 0x00000008;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var name = "test";
var p = CreateNamedPipe(@"\\.\pipe\" + name, PIPE_ACCESS_OUTBOUND, PIPE_TYPE_MESSAGE | PIPE_WAIT, 255, 0, 4096, 0xffffffff, IntPtr.Zero);
if (p.ToInt32() == -1)
{
throw new Exception("Error creating named pipe " + name + " . Internal error: " + Marshal.GetLastWin32Error().ToString());
}
var fs = new FileStream(new Microsoft.Win32.SafeHandles.SafeFileHandle(p, true), FileAccess.Write);
fs.Close();
}
}
}
這似乎工作得很好。 比我希望的要丑一點,但並非不可能。 感謝@David Browne 為我指明了正確的方向。
更完整的例子: https : //www.pinvoke.net/default.aspx/kernel32.createnamedpipe
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.