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

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

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); } } }}
