C# 无法从串行端口接收数据

C# 无法从串行端口接收数据,c#,serial-port,C#,Serial Port,[未解决] 我正在尝试接收数据并将其写入txt文件,我对此进行了检查并正确添加了eventHandler。打开等的顺序是相同的。但是,我无法接收数据,即使当我尝试打印(在SerialPort\u DataReceived内部)时,它也不会一无所获。我无法接收数据 p.CmdSerialPort.DataReceived无论我如何更改,都始终为空 有人能帮忙吗 class Program { private System.IO.Ports.SerialPort CmdSerialPor

[未解决]

我正在尝试接收数据并将其写入txt文件,我对此进行了检查并正确添加了eventHandler。打开等的顺序是相同的。但是,我无法接收数据,即使当我尝试打印(在
SerialPort\u DataReceived
内部)时,它也不会一无所获。我无法接收数据

p.CmdSerialPort.DataReceived
无论我如何更改,都始终为空

有人能帮忙吗

 class Program
{

    private System.IO.Ports.SerialPort CmdSerialPort;
    private StreamWriter swLog;
    private DateTime lastComm = DateTime.MinValue;
    private UdpClient udpClient_Cmd;
    private volatile bool _enabled_Cmd;
    public static int Ethernet_Packet_Header_Length = 14;
    public IPAddress IP { get; protected set; }
    public int Cmd_Port { get; protected set; }
    static void Main(string[] args)
    {
        Console.WriteLine("Please Enter Parameters: ");
        Program p = new Program();
        p.IP = IPAddress.Parse("....");//IP

        p.CmdSerialPort = new SerialPort();
        p.CmdSerialPort.Handshake = Handshake.None;
        p.CmdSerialPort.BaudRate = 9600;
        p.CmdSerialPort.Parity = Parity.None;
        p.CmdSerialPort.StopBits = StopBits.One;
        p.CmdSerialPort.DataBits = 8;

        //takes port, ethernet and filename inputs
        string s = Console.ReadLine();
        string[] input = s.Split(' ').ToArray();

        if (input.Length > 3)
            Console.WriteLine("Wrong input size!");

        string filename = input[2];//takes filename 
        //DEFAULT PATH ROOT
        String root = @".\\";
        string path_combined;

        filename += ".txt";
        path_combined = Path.Combine(root, filename);

        try
        {

            if (p.TryConnect(input[0]))//takes port name  eg.COM9
                p.swLog = File.CreateText(path_combined);

        }
        catch (System.IndexOutOfRangeException ex)
        {
            System.ArgumentException argEx = new System.ArgumentException("File creation failed!", ex);
            throw argEx;
        }



        p.Cmd_Port = Int32.Parse(input[1]);//takes port number  eg.4667

        p.Initialize();

        Console.ReadKey();

        p.Close2();

        p.Close();


    }//end of main

    ////////////////////////////////////////////////////////////
    // SERIAL PORT 
    ////////////////////////////////////////////////////////////

    private bool TryConnect(string portName)
    {

        try
        {

            CmdSerialPort.PortName = portName;
            CmdSerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
            CmdSerialPort.Open();

            if (CmdSerialPort.IsOpen)
            {

                return true;

            }
            return false;

        }
        catch (UnauthorizedAccessException e)
        {

            Debug.WriteLine(e.ToString());

            Debug.WriteLine(e.Message);

            return false;

        }

        catch (ArgumentOutOfRangeException e)
        {

            Debug.WriteLine(e.ToString());

            Debug.WriteLine(e.Message);

            return false;
        }
        catch (ArgumentException e)
        {

            Debug.WriteLine(e.ToString());

            Debug.WriteLine(e.Message);

            return false;

        }

    }

    internal void Close2()
    {
        if (CmdSerialPort.IsOpen)
        {

            CmdSerialPort.Close();

        }

        swLog.Close();

        swLog = null;

    }



    private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {

        lastComm = DateTime.Now;

        if (sender is SerialPort sp)
        {

            string indata = sp.ReadExisting();

            indata = indata.Trim(' ').Trim('\n').Trim('\r');

            WriteToFile($"{CmdSerialPort.PortName}\t{lastComm}\t{indata}");

        }

    }

    private void WriteToFile(string v)
    {

        swLog.WriteLine(v);

    }

}

您的程序在读取任何内容之前退出。您需要让它在
p.Initialize()
p.Close2()之间等待。请尝试
Console.ReadKey()
,这样它将一直运行到“按任意键”。您还应该处理
TryConnect
返回“false”…您尝试连接到哪个串行端口(Com1、Com2、Com3……)。代码中没有指定com编号的位置。UDP/IP连接代码与串行端口无关。@Fildor我根据您的建议更新了我的代码,它创建了一个文件,这意味着TryConnect返回true,而txt仍然为trueempty@Fildor我已经做了,我只是想让你通知我自己发现的,你的观点不同我知道,谢谢,我还在努力:/