Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from USB using C#?

Tags:

c#

usb

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 or explain the flow of the process i will greatly appreciate your help

like image 988
SamGMU Avatar asked Jun 16 '10 14:06

SamGMU


2 Answers

If you want to do development for USB, Jan Axelson's (the author of USB Complete) website is usually a good place to start.

Edit: Assuming it's a HID you want to communicate with this article could be useful and includes C# samples.

like image 64
Hans Olsson Avatar answered Nov 07 '22 02:11

Hans Olsson


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

    public override async Task<byte[]> 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

like image 24
Christian Findlay Avatar answered Nov 07 '22 04:11

Christian Findlay