在命名空间“System.IO.Ports”中找不到类型名称“SerialPort”

K. *_*sen 6 c# reference visual-studio

我正在使用 Visual Studio Community 2019 编写一个新的串口下载程序。我对 C# 比较陌生,但必须维护一个大型 C# 应用程序,该应用程序也使用串行端口来配置嵌入式设备。

有问题的(新)代码如下。“System.IO.Ports”using 语句没有任何效果(显示为灰色),问题是编译器不知道“SerialPort”是什么(请参阅代码后面的错误)。

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Drawing;

namespace PangeaUpdater
{
    class Download
    {
        const byte STX_CHAR = (byte)'\x2';
        const byte ETX_CHAR = (byte)'\x3';
        const byte DLE_CHAR = (byte)'\x10';

        const int MAX_DATA_PACKET_LEN = 128;
        private BinaryReader pkgStream = null;

        public SerialPort serialPort;

        private void Create(String comPort, String baudrate,         
            System.Windows.Forms.RichTextBox msgListBox,
            System.Windows.Forms.ProgressBar progressBar)
        {
            //Lots of stuff should be configurable but is not (yet)
            serialPort = new SerialPort(comPort,
                                    Convert.ToInt32(baudrate),
                                    Parity.None,
                                    8,
                                    StopBits.One);

            serialPort.Handshake = Handshake.None;

            serialPort.Open();
            serialPort.ReadTimeout = 1000;
            progBar = progressBar;
            messages = msgListBox;
         }

        public Download(String comPort,
                String baudrate,
                //String Product,
                System.Windows.Forms.RichTextBox msgListBox,
                System.Windows.Forms.ProgressBar progressBar)
        {
            Create(comPort, baudrate, /*Product,*/ msgListBox, progressBar);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

C:...\Download.cs(20,16,20,26): 错误 CS1069: 在命名空间“System.IO.Ports”中找不到类型名称“SerialPort”。此类型已转发到程序集“System.IO.Ports,Version=4.0.1.0,Culture=neutral,PublicKeyToken=cc7b13ffcd2ddd51”请考虑添加对该程序集的引用。

我已经检查了我维护的应用程序,该应用程序编译和运行良好。旧应用程序有一组引用,但新应用程序只有一组依赖项,但我认为这些非常相似或相同?

我怀疑添加参考是必需的,但我不知道需要什么。当我尝试在新应用程序中添加引用时,除了 COM 程序集之外,我什么也看不到。有负载,但不知道串行端口可能需要哪些负载。旧的配置应用程序没有提供任何线索,因为它在哪里找到 SerialPort 类型的引用。

有谁知道我可能错过了什么?

Ric*_*and 7

您可能需要添加对 System.ComponentModel.Component 的引用。请参阅:https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport ?view=netframework-4.8

如果它是 .NET 6 应用程序,您可能需要 VS2022 和 NuGet 包: https: //www.nuget.org/packages/System.IO.Ports/

(VS2019不支持.NET 6)


K. *_*sen 4

我发现了问题。就是我无意中选择了一个框架“核心”项目作为模板。作为 Visual Studio C# 的新手,我不明白为什么有这么多模板。这似乎是一系列令人困惑的项目类型,没有解释它们之间的细微差别。

不管怎样,谢谢你的建议。我认为我密切关注实际的错误消息,而没有充分关注此问题的其他症状,例如工具箱中的大多数组件都丢失了!