FileSystemWatcher位于System.IO名稱空間下,使用前需using System.IO;
FileSystemWatcher可以監控指定目錄下的文件刪除,創建,重命名等操作。在其構造函數中可以指定需要監控的目錄以及需要監控的特定文件類型。
其Created事件在指定目錄下創建文件的時候觸發。
然而在實際應用中我們常常需要在需要監控的目錄中文件創建完成時才作出相應的處理,而這個事件是在有文件創建的時候就觸發的,這在處理大文件的時候就容易出錯,因為文件還沒創建完成,比如復制一個大文件。這時候我們需要對創建的文件進行訪問的時候就會出現無法打開文件的異常。
很多網友都是通過循環檢查創建的文件大小變化來判斷文件是否完成的,這樣帶來了很大的系統性能損耗,而且不穩定。
其實我們可以使用一個變通的辦法,那就是在創建完大文件的時候創建一個同名的特定類型的小文件,前面我們已經說到FileSystemWatcher類是可以指定監控特定類型的文件的,所以我們就可以安全的處理創建的文件了。
FileSystemWatcher fsw = new FileSystemWatcher(@"D:\aaa");
fsw.Created += new FileSystemEventHandler(fsw_Created);
fsw.Created += new FileSystemEventHandler(fsw_Created);
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileWatch

{
public partial class FileWatch : Form
{
全局變量#region 全局變量
private FileSystemWatcher mWatch = null;
#endregion

窗體事件#region 窗體事件
public FileWatch()
{
InitializeComponent();
this.mWatch = new FileSystemWatcher();
this.mWatch.Changed += new FileSystemEventHandler(mWatch_Changed);
this.mWatch.Created += new FileSystemEventHandler(mWatch_Created);
this.mWatch.Deleted += new FileSystemEventHandler(mWatch_Deleted);
}
private void btnSelectPath_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
this.mWatch.Path = dlg.SelectedPath;
this.mWatch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.DirectoryName | NotifyFilters.FileName;
this.textBoxPath.Text = dlg.SelectedPath;
this.mWatch.EnableRaisingEvents = true;
}
}
#endregion

變化UI#region 變化UI
private delegate void ShowInfoHandler(String str);
private void ShowInfo(string strInfo)
{
if (this.InvokeRequired)
{
this.Invoke(new ShowInfoHandler(this.ShowInfo), new object[]
{ strInfo });
}
else
{
this.rtbHistory.AppendText(strInfo);
}
}
#endregion

監控事件#region 監控事件
void mWatch_Deleted(object sender, FileSystemEventArgs e)
{
ShowInfo(e.ChangeType.ToString() + "\t" + e.Name + "\r\n");
}
void mWatch_Created(object sender, FileSystemEventArgs e)
{
ShowInfo(e.ChangeType.ToString() + "\t" + e.Name + "\r\n");
}
void mWatch_Changed(object sender, FileSystemEventArgs e)
{
ShowInfo(e.ChangeType.ToString() + "\t" + e.Name + "\r\n");
}
#endregion
}
}

