溫馨提示×

C# DataReceived事件的監(jiān)控與日志記錄

c#
小樊
85
2024-08-08 21:06:42
欄目: 編程語言

在C#中,可以通過DataReceived事件來監(jiān)控?cái)?shù)據(jù)的接收情況,并將接收到的數(shù)據(jù)記錄到日志中。以下是一個簡單的示例代碼:

using System;
using System.IO.Ports;

class Program
{
    static void Main()
    {
        SerialPort serialPort = new SerialPort("COM1", 9600);
        serialPort.DataReceived += SerialPort_DataReceived;
        serialPort.Open();

        Console.WriteLine("Press any key to stop monitoring...");
        Console.ReadKey();

        serialPort.Close();
    }

    private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort serialPort = (SerialPort)sender;
        string data = serialPort.ReadExisting();
        
        // 將接收到的數(shù)據(jù)記錄到日志中
        LogData(data);
    }

    private static void LogData(string data)
    {
        using (StreamWriter sw = new StreamWriter("log.txt", true))
        {
            sw.WriteLine($"[{DateTime.Now}] Received: {data}");
        }
    }
}

在上面的示例中,我們首先創(chuàng)建了一個SerialPort對象并打開串口,然后通過DataReceived事件來監(jiān)控?cái)?shù)據(jù)的接收情況。當(dāng)數(shù)據(jù)被接收時,會調(diào)用SerialPort_DataReceived方法將數(shù)據(jù)記錄到日志中。日志文件將會在程序運(yùn)行目錄生成一個log.txt文件,并將接收到的數(shù)據(jù)以時間戳的形式記錄在文件中。

通過以上示例,我們可以實(shí)現(xiàn)對數(shù)據(jù)的接收情況進(jìn)行監(jiān)控,并將接收到的數(shù)據(jù)記錄到日志中,方便后續(xù)的分析和處理。

0