How to Utilize System.IO.Ports.SerialPort in a NET Maui

Yusuf 791 Reputation points
2023-07-25T05:18:58.2533333+00:00

Hello

I am currently working on a Maui app that communicates with an Arduino board using a SerialPort. The code works perfectly in a console application, but when I tried running it in a Maui project, I encountered the following error: "CS1069: The 'SerialPort' constructor does not exist." I have attempted various solutions, but I am still unable to resolve this error.

Here's the relevant portion of my code:

using System;
using System.IO.Ports;
using System.Threading;
using Microsoft.Maui.Controls;

namespace ArduinoMessageReceiver
{
    public partial class MainPage : ContentPage
    {
        static SerialPort _serialPort;

        public MainPage()
        {
            InitializeComponent();
            _serialPort = new SerialPort(); // CS1069 error here
            _serialPort.PortName = "COM5";
            _serialPort.BaudRate = 9600;
            _serialPort.Open();
            while (true)
            {
                string a = _serialPort.ReadExisting();
                portMessage.Text += a;
                Thread.Sleep(200);
            }
        }
    }
}

I would greatly appreciate your expertise in helping me understand the cause of this error and finding a solution to make my SerialPort communication work in my Maui app.

If there are any specific libraries or workarounds that are compatible with Maui for serial communication, I would be grateful to know about them. Any suggestions, code examples, or insights would be immensely helpful to me in overcoming this challenge.

Thank you all for your time and support. I look forward to your valuable assistance.

Developer technologies | .NET | .NET MAUI
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2023-07-26T02:03:24.9833333+00:00

    Hello,

    After investigating, I called _serialPort = new SerialPort(); in the MAUI project, but no error message appears.

    Since CS1069 errors are usually caused by not being able to reference classes in the namespace, open the NugetPackage Manager in your MAUI project and see if System.IO.Ports is installed.

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.