user19232186
user19232186

Reputation:

C# - SerialPort does not exist in the current context - System.IO.Ports

My code:

using System;
using System.ComponentModel;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;

namespace MyProject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (object portName in SerialPort.GetPortNames())
            {
                comboBox1.Items.Add(portName);
            }
        }

Everything works fine apart from the error: The name 'SerialPort' does not exist in the current context

I don't understand because I have using System.IO.Ports; .NET 6.0 Windows Forms C#

Upvotes: 0

Views: 2029

Answers (1)

djv
djv

Reputation: 15782

In .NET core you will need to install the NuGet package System.IO.Ports.

enter image description here

You can do it via either the intellisense or in the NuGetPackageManager for your application

enter image description here

Make sure nuget.org is selected in the NuGet Package Manager

enter image description here

and make sure that your nuget.org source is https://api.nuget.org/v3/index.json (in Visual Studio 2022, C# 6, as of Oct 2022)

enter image description here

If you had taken code from a sample based on .NET Framework, the reference is added by default and the using statement would be enough.

Upvotes: 2

Related Questions