Arduino, USB and C#

Hello!
I am going to connect my Arduino displaying chars on serial monitor from time to time, which will be read by a program on the computer written in C #. I ran into a bug: CS 1069 which is related to SerialPort.
Has anyone encountered this problem and know how to fix it?
Thank you in advance!

using System;
using System.IO;
using System.IO.Ports;

namespace MyProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            SerialPort SP = new SerialPort("COM4", 9600);
            try
            {
                SP.Open();
                SP.Close();
            }
            catch(InvalidOperationException ex)
            {
                Console.WriteLine(ex);
            }
        }   
    }
}

SerialPort

Why are you asking about a C# bug on the Arduino forum ?

It is related to the project done with arduino.

If you had a problem with the Arduino would you ask for help in a C# forum ?

Skilled programmers can be anywhere.

True, but you are more likely to find skilled C# programmers in a C# forum

I asked this question there too.

What project type have you created? System.IO.Ports doesnt work with .Net Core, I suspect you have created a .Net core console app.

Also, just FYI. You are only catching an InvalidOperation Exception. Any other exception occurs and your program is going to bomb out.

The base Exception exception will cover all. Generally we would say its not best practice to just catch the generic as you miss the extended details in other exception types and it also allows for different flows based on type of exception. Think about how you want to handle them. If you want to handle a specific one then include a catch block for that, but put the generic one after it to catch all others.