简体   繁体   中英

.NET Core: Read /dev/ file

Connecting my RFID reader to my Linux machine it get installed automatically. I can see its output using hexdump /dev/hidraw0 .

I want to read that input using C# .NET Core. I works fine using Pinvoke. Here the opening part (details over here ):

[DllImport("libc")]
public static extern int open(string pathname, OpenFlags flags);

int fd = open("/dev/hidraw0", OpenFlags.O_RDONLY);

Is it possible to do the opening and reading using .NET Core methods? /dev/hidraw0 is just a (device) file, right? Wouldn't it be possible to use FileStream or BinaryReader ? The problem I am facing: I only find methods which read available data, but I need a blocking read method which wait until data is available and then return it. Or maybe there is a DataAvailable event or alike?

Basically my question boils down to: Am a stuck with libc's read() and open() methods or is there a .NET Core way for reading /dev/ files?

I think this could help you: Linux & Dotnet – Read from a device file

public void ReadDeviceStream(CancellationToken stoppingToken) 
{
  // Use the device file
  var targetFile = new FileInfo("/dev/inputs/event1");
  // Open a stream
  using (FileStream fs = targetFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  {
    stoppingToken.Register(() => fs?.Close());
    int blockId = 1;
    // A big buffer, for simplicity purpose and to receive the entire touch report. We should use
    // the proper buffer size based on the event size. Note that we could also
    // use the binary reader
    var buffer = new byte[1024];
    // Read until the token gets cancelled
    while (!stoppingToken.IsCancellationRequested && fs.Read(buffer) > 0)
    {
      ShowBinaryContent(blockId, buffer);
      blockId++;
    }
  }
}
public void ShowBinaryContent(int blockId, byte[] buffer)
{
  Console.WriteLine($"Block #{blockId}");
  Console.WriteLine(BitConverter.ToString(bytes)); // Hex format: AB-1D...
  Console.WriteLine(string.Empty);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM