.NET Core - 在visual studio代码中使用System.IO.Ports.SerialPort

时间:2017-03-10 06:05:20

标签: c# serial-port visual-studio-code .net-core

我尝试使用带有.Net Core的visual studio代码创建一个控制台应用程序并获取所有可用端口。如何在visual studio代码中使用System.IO.Ports.SerialPort class? 我尝试使用using语句声明它,但唯一可用的是名称空间Compression中的MemoryMappedFilesSystem.IO

我正在使用.Net Core 1.1.1 SDK

4 个答案:

答案 0 :(得分:5)

如果您使用的是Linux操作系统,则可以使用SerialPortStream库。它需要libserial二进制文件,我只能为linux编译它(不适用于MacOS或Windows)。

其他方式是使用Mono实现和Mono.Posix.NETStandard包。这种方式仅适用于NETStandard 2.0项目。

我将Mono的System.IO.Ports类的源代码复制到我的NETStandard 2.0项目中,将Mono.Posix.NETStandard,Microsoft.Win32.Registry引用和<AllowUnsafeBlocks>true</AllowUnsafeBlocks>部分添加到我的.csproj文件中。它适用于MacOs和Windows。

答案 1 :(得分:2)

对于那些几年后来此职位的人...

从.NET Core 2.0开始,可以使用System.IO.Ports package

答案 2 :(得分:1)

请使用.NET API浏览器。 .NET Core 1.1不存在SerialPort: https://docs.microsoft.com/en-us/dotnet/api/?term=serialport&view=netcore-1.1 但它是在.NET Core 2.0中添加的: https://docs.microsoft.com/en-us/dotnet/api/?term=serialport&view=netcore-2.0 您始终可以从主框架添加对System.IO.dll的引用以获取SerialPort,但是您不符合.NET Core 1.1(无法移植到Linux,MacOS等)

答案 3 :(得分:-4)

System.IO.Ports将出现在system.dll中,因此默认情况下,它会在您创建项目时添加到项目中。

然后你需要添加

Using System.IO.Ports Namespace to your class 

这是为我们提供可用端口的示例。

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);
      }
}