Home > Software engineering >  C# - SerialPort does not exist in the current context - System.IO.Ports
C# - SerialPort does not exist in the current context - System.IO.Ports

Time:10-28

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#

CodePudding user response:

Thanks to @djv, we fixed it by doing:

Project -> Manage Nuget Packages Add a new package source with the source: 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.

  •  Tags:  
  • c#
  • Related