Reading data from USB using C#?

后端 未结 2 385
心在旅途
心在旅途 2021-01-05 17:46

I do not want to read serial port nor other possible easy shortcuts please. I would like to know how to read a USB port in my laptop using C#. whether you can suggest a site

2条回答
  •  执笔经年
    2021-01-05 18:28

    The assumption here is that you want to read data on Windows. Here is a code sample:

        public override async Task ReadAsync()
        {
            return await Task.Run(() =>
            {
                var bytes = new byte[ReadBufferSize];
                //TODO: Allow for different interfaces and pipes...
                var isSuccess = WinUsbApiCalls.WinUsb_ReadPipe(_DefaultUsbInterface.Handle, _DefaultUsbInterface.ReadPipe.WINUSB_PIPE_INFORMATION.PipeId, bytes, ReadBufferSize, out var bytesRead, IntPtr.Zero);
                HandleError(isSuccess, "Couldn't read data");
                Tracer?.Trace(false, bytes);
                return bytes;
            });
        }
    
        [DllImport("winusb.dll", SetLastError = true)]
        public static extern bool WinUsb_ReadPipe(SafeFileHandle InterfaceHandle, byte PipeID, byte[] Buffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped);
    

    All code and samples (including other platforms) can be found here: https://github.com/MelbourneDeveloper/Device.Net

提交回复
热议问题