我正在尝试使用互操作获取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
将返回假。是什么导致那个失败?
您应该使用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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句