0

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#

1 Answers1

2

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.

djv
  • 15,168
  • 7
  • 48
  • 72
  • I tried that already. "No packages found" in Nuget Package manager when I search for : "System.IO.Ports" –  Oct 27 '22 at 19:04
  • Is your source nuget.org? Do you have any IT issue blocking access to the server? – djv Oct 27 '22 at 19:09
  • Project -> Manage Nuget Packages -> Browse -> System.IO.Ports search has no results. Heres a picture: https://ibb.co/yd1bH61 –  Oct 27 '22 at 19:24
  • Check your image, the `Package Source` to the right is `Microsoft Visual Studio Offline Packages`. Can you change it to `nuget.org`? – djv Oct 27 '22 at 19:26
  • Like this? https://ibb.co/P13Z90N I'm getting an error. [Package source] The V2 feed at 'https://www.nuget.org/Search()?$filter=IsAbsoluteLatestVersion&searchTerm=''&targetFramework='net6.0-windows7.0'&includePrerelease=true&$skip=0&$top=26&semVerLevel=2.0.0' returned an unexpected status code '404 Not Found'. An error occurred while retrieving package metadata for 'system.security.cryptography.encoding' from source 'Package source'. [Package source] The V2 feed at 'https://www.nuget.org/Search()? –  Oct 27 '22 at 19:31
  • I don't know. See my latest picture. nuget.org and the offline one are both available as options for me in the dropdown. If you can't select it from there then you have another issue – djv Oct 27 '22 at 19:33
  • In my settings, the address is `https://api.nuget.org/v3/index.json` – djv Oct 27 '22 at 19:35
  • 1
    That worked with that source. Thank you so much @djv –  Oct 27 '22 at 19:41