C#利用FileSystemWatcher对文件进行监控

2025-06-20 23:12:43

1、打开VS,选择Visual C#模板创建WPF应用程序。输入名称FileSystemWatcherTest,并指定其位置,点击确认按钮进入代码编写界面。

C#利用FileSystemWatcher对文件进行监控

3、添加一个名为MyWatcher的新类。可点击VS菜单项中的【项目】在其下拉菜单中找到【添加类】并点击,弹出添加新项窗口,在点击C#项中【类】,输入名称MyWatcher,点击【添加】按钮

C#利用FileSystemWatcher对文件进行监控

5、在Form1页面中添加复制粘贴如下代码:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace FileSystemWatcherTest{ public partial class Form1 : Form { public Form1() { InitializeComponent(); MyWatcher mwatcher = new MyWatcher(this, "1.txt"); } public void TxtChanged(string path) { System.IO.StreamReader sr = new System.IO.StreamReader(path); string str = sr.ReadToEnd(); sr.Close(); RichTextBox1Text = str; } private delegate void RefleshUI(string s); private void Thread(string s)//UI线程要做的事情 { this.richTextBox1.Text = s; } public string RichTextBox1Text { set { this.richTextBox1.Invoke(new RefleshUI(Thread), value); } } }}

C#利用FileSystemWatcher对文件进行监控
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢