c# txt文档的实时显示,用来查看发送接收指令

发布于:2025-03-14 ⋅ 阅读:(9) ⋅ 点赞:(0)

在这里插入图片描述
通讯历史按钮

        private void uiButton1_Click(object sender, EventArgs e)
        {
            try
            {
                logf = new logF();
                logf.Show();
            }
            catch (Exception)
            {

                throw;
            }     
        }

主页面关闭函数(点击保存就为true true就不删除)

        private void page1_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 关闭应用时删除txt文件 为true就不删除
            if (logF.savelog== false)
            {
                if (File.Exists(logF.filePath))
                {
                    File.Delete(logF.filePath);
                }
            }

            Application.Exit();
        }

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;

namespace WindowsFormsApp1
{
    public partial class logF : UIForm
    {
        public logF()
        {
            InitializeComponent();
            Application.EnableVisualStyles();
            //Application.Run(new MainForm());
            MainForm();
        }
        private FileSystemWatcher fileWatcher;
        public static string filePath = @"C:\log\run.txt";
        public static bool savelog=false;
        public void MainForm()
        {
             初始化RichTextBox
            //richTextBox1 = new RichTextBox();
            //richTextBox1.Dock = DockStyle.Fill;
            //this.Controls.Add(richTextBox1);

            // 初始化FileSystemWatcher
            fileWatcher = new FileSystemWatcher();
            fileWatcher.Path = Path.GetDirectoryName(filePath);
            fileWatcher.Filter = Path.GetFileName(filePath);
            fileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;

            // 绑定事件处理程序
            fileWatcher.Changed += OnFileChanged;
            fileWatcher.EnableRaisingEvents = true;

            // 初始加载文件内容
            LoadFileContent();
        }

        private void LoadFileContent()
        {
            try
            {
                // 读取文件内容并显示在RichTextBox中
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (StreamReader reader = new StreamReader(fs))
                {
                    richTextBox1.Text = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error reading file: " + ex.Message);
            }
        }

        private void OnFileChanged(object sender, FileSystemEventArgs e)
        {
            在UI线程上更新RichTextBox内容
            //this.Invoke((MethodInvoker)delegate
            //{
            //    LoadFileContent();
            //});
            if (this.IsHandleCreated) // 确保句柄已存在
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    LoadFileContent();
                });
            }
        }
        private void logF_Load(object sender, EventArgs e)
        {

             读取txt文件内容并显示在文本框中
            //if (File.Exists(filePath))
            //{
            //    string content = File.ReadAllText(filePath);
            //    richTextBox1.Text = content;
            //}
            //else
            //{
            //    MessageBox.Show("文件不存在!");
            //}

        }

        private void uiButton7_Click(object sender, EventArgs e)
        {
            savelog = true;
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@"C:\log");
        }
    }
}

log.cs
在这里插入图片描述

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
    internal class log
    {
        public static void SaveLog(string log, string filename = @"C:\log\run.txt")
        {
            string pathA = filename.Substring(0, filename.LastIndexOf("\\"));
            if (!Directory.Exists(pathA))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(pathA);
                directoryInfo.Create();
            }
            string filepathA = filename;
            try
            {
                String time = DateTime.Now.ToString("[yyyy-MM-dd hh:mm:ss]");
                time += log;
                if (!File.Exists(filepathA))
                {
                    using (StreamWriter sw = File.CreateText(filepathA))
                    {
                        sw.WriteLine(time);
                        sw.Close();
                    }
                }
                else
                {
                    {
                        using (StreamWriter sw = File.AppendText(filepathA))
                        {
                            sw.WriteLine(time);
                            sw.Close();
                        }
                    }

                }
            }
            catch
            {
                // MessageBox.Show("log异常" + ee.ToString());
            }
        }

    }
}

log.SaveLog("要保存的内容");