標籤:change ogre ini txt dial 位置 rms 調用 通過
如果需要知道修改檔案或目錄的時間,可以通過FileSystemWatcher類,這個類提供了一下應用程式可以捕獲的事件,應用程式可以對事件作出響應。
使用FileSystemWatcher非常簡單,首先必須設定一些屬性,指定監控的位置、內容以及引發應用程式要處理事件的時間,然後給FileSystemWatcher提供定製事件處理常式的地址。當事件發生時,FileSystemWatcher就調用這些屬性,然後開啟FileSystemWatcher,等待事件。
1、在啟用FileSystemWatcher對象之前必須設定的屬性:
2、設定了屬性之後,必須為4個事件Changed、Created、Deleted、Renamed編寫事件處理常式。
3、設定了屬性和事件後,將EnableRaisingEvents屬性設定為true,就可以開始監控工作了。
樣本:
建立如下表單:
表單內容:
代碼:
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;namespace WindowsFormsApplication5{ public partial class Form1 : Form { private FileSystemWatcher watcher; private delegate void updateTextDEL(string text); public Form1() { InitializeComponent(); watcher = new FileSystemWatcher(); watcher.Deleted += watcher_Deleted; watcher.Renamed += watcher_Renamed; watcher.Changed += watcher_Changed; watcher.Created += watcher_Created; } public void UpdateText(string text) { lbWatch.Text = text; } void watcher_Created(object sender, FileSystemEventArgs e) { StreamWriter sw = new StreamWriter("log.txt", true); sw.WriteLine("File:{0} created", e.FullPath); sw.Close(); this.BeginInvoke(new updateTextDEL(UpdateText), "created"); } void watcher_Changed(object sender, FileSystemEventArgs e) { StreamWriter sw = new StreamWriter("log.txt", true); sw.WriteLine("File:{0}{1}", e.FullPath, e.ChangeType, ToString()); sw.Close(); this.BeginInvoke(new updateTextDEL(UpdateText), "changed"); } void watcher_Renamed(object sender, RenamedEventArgs e) { StreamWriter sw = new StreamWriter("log.txt", true); sw.WriteLine("File:renamed from{0}to{1}", e.OldName, e.FullPath); sw.Close(); this.BeginInvoke(new updateTextDEL(UpdateText), "renamed"); } void watcher_Deleted(object sender, FileSystemEventArgs e) { StreamWriter sw = new StreamWriter("log.txt", true); sw.WriteLine("File:{0}deleted", e.FullPath); sw.Close(); this.BeginInvoke(new updateTextDEL(UpdateText), "deleted"); } private void btnBrowser_Click(object sender, EventArgs e) { if(openFileDialog1.ShowDialog()!=DialogResult.Cancel) { txbLocatin.Text = openFileDialog1.FileName; } } private void btnWatch_Click(object sender, EventArgs e) { watcher.Path = Path.GetDirectoryName(txbLocatin.Text); watcher.Filter = Path.GetFileName(txbLocatin.Text); watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters .Size; lbWatch.Text = "watching" + txbLocatin.Text; watcher.EnableRaisingEvents = true; } }}
c#之監控檔案結構