且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取使用C#连接到命名管道服务器的客户端的进程ID

更新时间:2022-01-08 22:05:10

该代码的主要问题在于,它无法执行正确的错误处理.您需要检查GetNamedPipeClientProcessId的返回值以检测错误.

The main problem with that code, is that it does not perform correct error handling. You need to check the return value of GetNamedPipeClientProcessId to detect an error.

[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetNamedPipeClientProcessId(IntPtr Pipe, out uint ClientProcessId);
public static uint getNamedPipeClientProcID(NamedPipeServerStream pipeServer)
{
    UInt32 nProcID;
    IntPtr hPipe = pipeServer.SafePipeHandle.DangerousGetHandle();
    if (GetNamedPipeClientProcessId(hPipe, out nProcID))
        return nProcID;
    return 0;
}