为什么我不能使用`WTSVirtualChannelQuery`返回的句柄?

时间:2018-04-30 06:31:32

标签: c# remote-desktop

尝试使用RDP动态虚拟通道。我将WTSVirtualChannelQuery的{​​{1}}结果传递给WTSVirtualFileHandle,但它会抛出各种异常。为什么呢?

呼叫:

FileStream

例外:

public static FileStream Open(string channelName, WTS_CHANNEL_OPTION option = WTS_CHANNEL_OPTION.DYNAMIC)
{
    // Open
    SafeFileHandle pFile = null;
    using (var sfh = WTSVirtualChannelOpenEx(WTS_CURRENT_SESSION, channelName, option))
    {
        WtsAllocSafeHandle pBuffer = null;
        try
        {
            int cbReturned;
            if (!WTSVirtualChannelQuery(sfh, WTS_VIRTUAL_CLASS.FileHandle, out pBuffer, out cbReturned)
                || cbReturned < IntPtr.Size)
            {
                throw new Win32Exception();
            }
            pFile = new SafeFileHandle(Marshal.ReadIntPtr(pBuffer.DangerousGetHandle()), false);
        }
        finally
        {
            pBuffer?.Dispose();
        }
    }

    // create
    return new FileStream(pFile, FileAccess.ReadWrite, bufferSize: 32 * 1024 * 1024, isAsync: true);
}

System.ArgumentException: Handle does not support asynchronous operations.  The parameters to the FileStream constructor may need to be changed to indicate that the handle was opened synchronously (that is, it was not opened for overlapped I/O).
    at System.IO.FileStream..ctor(SafeFileHandle handle, FileAccess access, Int32 bufferSize, Boolean isAsync)

1 个答案:

答案 0 :(得分:0)

调用System.IO.IOException: The handle is invalid. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.VerifyHandleIsSync() at System.IO.FileStream..ctor(SafeFileHandle handle, FileAccess access, Int32 bufferSize, Boolean isAsync) 后,WTSVirtualChannelQuery返回的句柄似乎无效。在致电WTSFreeMemory之前致电DuplicateHandle并使用重复的句柄。

WTSFreeMemory