C# 与 GetNamedPipeClientComputerName 互操作

C# Interop with GetNamedPipeClientComputerName

我正在尝试使用互操作调用获取 C# 命名管道客户端的进程 ID 和计算机名称:

[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetNamedPipeClientProcessId(IntPtr Pipe, out uint ClientProcessId);

private static uint GetClientProcessID(NamedPipeServerStream pipeServer)
{
    uint processId;
    IntPtr pipeHandle = pipeServer.SafePipeHandle.DangerousGetHandle();
    if (GetNamedPipeClientProcessId(pipeHandle, out processId))
    {
        return processId;
    }
    return 0;
}

[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetNamedPipeClientComputerName(IntPtr Pipe, out string ClientComputerName, uint ClientComputerNameLength);

private static string GetClientComputerName(NamedPipeServerStream pipeServer)
{
    string computerName;
    uint buffer = 32768;
    IntPtr pipeHandle = pipeServer.SafePipeHandle.DangerousGetHandle();
    if (GetNamedPipeClientComputerName(pipeHandle, out computerName, buffer))
    {
        return computerName;
    }
    return null;
}

GetNamedPipeClientProcessId 调用正常,但 GetNamedPipeClientComputerName 返回 false。是什么导致那个失败?

您应该使用 StringBuilder 而不是 String:

[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetNamedPipeClientComputerName(IntPtr Pipe, StringBuilder ClientComputerName, uint ClientComputerNameLength);

那么,你需要这样调用它:

var computerName = new StringBuilder(buffer);
...
if (GetNamedPipeClientComputerName(pipeHandle, computerName, buffer))
{
    return computerName.ToString();
}
else throw new Win32Exception();