1、FileSystemWatcher用途:
FileSystemWatcher 元件用來監(jiān)視檔案系統(tǒng),而當檔案系統(tǒng)所包含的目錄或檔案變更時,也可以利用它來回應(yīng)。這讓您能夠在特定檔案或目錄被建立、修改或刪除時快速且容易啟動商務(wù)處理流程。
注:FileSystemWatcher元件是設(shè)計來監(jiān)視目錄內(nèi)的變更,而不是根目錄屬性本身的變更。Changed:變更目錄或檔案的大小、系統(tǒng)屬性、上次寫入時間、上次存取時間或安全性權(quán)限時引發(fā)。
2、FileSystemWatcher常用屬性
3、FileSystemWatcher常用事件
4、FileSystemWatcher中Filter屬性通配符說明
5、FileSystemWatcher中NotifyFilter枚舉值說明
以上可組合此枚舉的成員以監(jiān)視多種更改。組合時用“|”連接。
6、使用方法:
在窗體中拖入FileSystemWatcher控制項。
設(shè)定需要用的事件 編寫事件方法
using System.IO;
namespace FileSystemWatcherDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
UsingFileSystemWatcher();
}
/// <summary>
/// 使用FileSystemWatcher方法
/// </summary>
void UsingFileSystemWatcher()
{
//6.2
//FileSystemWatcher:偵聽文件系統(tǒng)更改通知,并在目錄或目錄中的文件發(fā)生更改時引發(fā)事件。
//獲取或設(shè)置要監(jiān)視的目錄的路徑。
fswWatcher.Path = @"D:\upload";
//獲取或設(shè)置要監(jiān)視的更改類型。
fswWatcher.NotifyFilter = NotifyFilters.LastWrite|NotifyFilters.FileName|NotifyFilters.LastAccess ;
//獲取或設(shè)置篩選字符串,用于確定在目錄中監(jiān)視哪些文件。
//此處只能監(jiān)控某一種文件,不能監(jiān)控件多種文件,但可以監(jiān)控所有文件
fswWatcher.Filter = "*.doc";
//獲取或設(shè)置一個值,該值指示是否監(jiān)視指定路徑中的子目錄。
fswWatcher.IncludeSubdirectories = true;
#region 6.3 觸發(fā)的事件
//文件或目錄創(chuàng)建時事件
fswWatcher.Created += new FileSystemEventHandler(fswWatcher_Created);
//文件或目錄變更時事件
fswWatcher.Changed += new FileSystemEventHandler(fswWatcher_Changed);
//文件或目錄重命名時事件
fswWatcher.Renamed += new RenamedEventHandler(fswWatcher_Renamed);
//文件或目錄刪除時事件
fswWatcher.Deleted += new FileSystemEventHandler(fswWatcher_Deleted);
#endregion
//獲取或設(shè)置一個值,該值指示是否啟用此組件。
fswWatcher.EnableRaisingEvents = true;
}
#region 6.4 觸發(fā)事件的方法
/// <summary>
/// 文件或目錄創(chuàng)建時事件方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void fswWatcher_Created(object sender, FileSystemEventArgs e)
{
MessageBox.Show("有新文件");
}
/// <summary>
/// 文件或目錄變更時事件的方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void fswWatcher_Changed(object sender, FileSystemEventArgs e)
{
}
/// <summary>
/// 文件或目錄重命名時事件的方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void fswWatcher_Renamed(object sender, RenamedEventArgs e)
{
}
/// <summary>
/// 文件或目錄刪除時事件的方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void fswWatcher_Deleted(object sender, FileSystemEventArgs e)
{
}
#endregion
}
}