.NET Core - Use System.IO.Ports.SerialPort in visu

2019-04-25 18:04发布

问题:

I'm trying to create an console application using visual studio code with .Net Core and get all available ports. How to use System.IO.Ports.SerialPort class in visual studio code? I try to declare it with using statement but the only available is Compression and MemoryMappedFiles in namespace System.IO.

I'm using .Net Core 1.1.1 SDK

回答1:

If you are using linux OS you can use SerialPortStream library. It requires the libserial binaries and I was able to compile it only for linux (not for MacOS or Windows).

Other way is using the Mono implementation and Mono.Posix.NETStandard package. This way works only for NETStandard 2.0 projects.

I copied sources of System.IO.Ports classes from Mono into my NETStandard 2.0 project, added the Mono.Posix.NETStandard, Microsoft.Win32.Registry references and included <AllowUnsafeBlocks>true</AllowUnsafeBlocks> section into my .csproj file. And it works on MacOs and Windows.



回答2:

Please use the .NET API Browser. SerialPort not present for .NET Core 1.1: https://docs.microsoft.com/en-us/dotnet/api/?term=serialport&view=netcore-1.1 but it was added in .NET Core 2.0: https://docs.microsoft.com/en-us/dotnet/api/?term=serialport&view=netcore-2.0 You can always add reference to System.IO.dll from main Framework to get the SerialPort, but then You are not .NET Core 1.1 conform (cannot port to Linux, MacOS etc)



回答3:

System.IO.Ports will present in the system.dll so by default it will be added to your project when you create it.

then you need to add

Using System.IO.Ports Namespace to your class 

This is sample which will give us the Available ports.

private void getAllAvailablePorts()
 {
     // Get a list of serial port names.
     string[] ports = SerialPort.GetPortNames();

     Console.WriteLine("The following serial ports were found:");

     // Display each port name to the console.
     foreach (string port in ports)
     {
       Console.WriteLine(port);
      }
}