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

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

相关文章:

  • Linux练级宝典->基础IO
  • ​【C++设计模式】第二十二篇:访问者模式(Visitor)
  • HTML块级元素和内联元素(简单易懂)
  • Scrum介绍(一种Agile敏捷开发框架,主要用于复杂项目的管理和交付。其核心思想是通过迭代、增量的方式,快速响应变化,持续交付高价值成果)
  • 基于Python+SQLite实现校园信息化统计平台
  • 32单片机——KEY
  • Java 泛型
  • 生活之味:苦与甜的交织-中小企实战运营和营销工作室博客
  • 大模型叙事下的百度智能云:比创新更重要的,是创新的扩散
  • 第九课:WebSocket与实时通信技术解析
  • TCP三次握手与四次挥手详解:建立与断开连接的底层逻辑
  • mysql主从复制
  • python pip及常用国内镜像源
  • Java爬虫测试淘宝快递费接口的完整指南
  • Visual Studio 安装及使用教程(Windows)【安装】
  • QT系列教程(15) 鼠标事件
  • LuaJIT 学习(1)—— LuaJIT介绍
  • RabbitMQ重复消费如何解决
  • flutter 如何与原生框架通讯安卓 和 ios
  • 虚拟展览馆小程序:数字艺术与文化展示的新形式探索
  • 解放日报:服务国家战略,加快建成科技创新高地
  • 国务院任免国家工作人员:颜清辉任人社部副部长
  • 200枚篆刻聚焦北京中轴线,“印记”申遗往事
  • 解放日报:持续拿出排头兵姿态先行者担当
  • 港交所与香港证监会就“中概股回流意向”已与部分相关企业进行接触
  • 西班牙葡萄牙遭遇史上最严重停电:交通瘫了,通信崩了,民众疯抢物资