在C#中打开到文件描述符的管道连接 [英] Opening pipe connection to a file descriptor in C#

查看:82
本文介绍了在C#中打开到文件描述符的管道连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旧版应用程序,在该应用程序中它从文件描述符3的客户端程序中读取消息.这是一个外部应用程序,因此无法更改.客户端是用C#编写的.我们如何在C#中打开到特定文件描述符的连接?我们可以使用AnonymousPipeClientStream()之类的东西吗?但是我们如何指定要连接的文件描述符?

I have a legacy app where it reads message from a client program from file descriptor 3. This is an external app so I cannot change this. The client is written in C#. How can we open a connection to a specific file descriptor in C#? Can we use something like AnonymousPipeClientStream()? But how do we specify the file descriptor to connect to?

推荐答案

不幸的是,如果不先P/调用本机Windows API,您将无法做到这一点.

Unfortunately, you won't be able to do that without P/Invoking to the native Windows API first.

首先,您将需要通过本地P/Invoke调用打开文件描述符.这是通过OpenFileById WINAPI函数完成的. 在MSDN上,使用方法 href ="http://social.msdn.microsoft.com/forums/en-US/windowssearch/thread/4b71fcb3-bea9-4cfb-bdb7-2f1a91522ea6/" rel ="noreferrer">这是另一个链接在MSDN论坛上进行了详细说明,并此处有一些帮助(pinvoke.net)关于如何构建您的P /呼叫.

First, you will need to open your file descriptor with a native P/Invoke call. This is done by the OpenFileById WINAPI function. Here's how to use it on MSDN, here's an other link explaining it in detail on the MSDN forums, and here's some help (pinvoke.net) on how to construct your P/Invoke call.

一旦获得了文件句柄,就需要将其包装在SafeFileHandle中,这次是在安全的托管C#中:

Once you got the file handle, you need to wrap it in a SafeFileHandle, this time in safe, managed C#:

// nativeHandle is the WINAPI handle you have acquired with the P/Invoke call
SafeFileHandle safeHandle = new SafeFileHandle(nativeHandle, true);

现在您可以直接打开文件流:

Now you can open the file stream directly:

Stream stream = new FileStream(safeHandle, FileAccess.ReadWrite);

从这一点上讲,您可以将其用作C#中的任何其他文件或流.完成操作后,别忘了处置对象.

And from this point you can use it as any other file or stream in C#. Don't forget to dispose your objects once you're done.

这篇关于在C#中打开到文件描述符的管道连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆