当前位置: 首页 > article >正文

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

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

        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("要保存的内容");

http://www.kler.cn/a/583698.html

相关文章:

  • 如何简单获取三个月免费试用的SSL证书
  • AI对前端开发的冲击
  • 第十课:项目部署与运维:从开发到生产
  • 仅仅使用pytorch来手撕transformer架构(1):位置编码的类的实现和向前传播
  • springcloud gateway搭建及动态获取nacos注册的服务信息信息
  • aws(学习笔记第三十二课) 深入使用cdk(API Gateway + event bridge)
  • C++算法学习2:二分算法精讲
  • 什么是SWIFT支付系统
  • X509TrustManager信任SSL证书
  • Springfox、Springdoc和Swagger
  • EtherCAT OpenEuler Web控制启动
  • 华为OD机试-机场航班调度程序(Java 2024 D卷 100分)
  • 玩转python:掌握Python数据结构之Trie树
  • 线性回归机器学习
  • 数据类设计_图片类设计之1_矩阵类设计(前端架构基础)
  • linux docker 安装dify本地运行,及部署后运行出现502问题
  • Redis:常见数据类型和单线程模型
  • 反射、 Class类、JVM的类加载机制、Class的常用方法
  • 【pyenv+venv组合来使用Python虚拟环境的方法】
  • 大脑宏观结构中的富集俱乐部:图论分析视角