[.net]監控檔案系統的目錄變更或檔案變更(FileSystemWatcher)

  • 531
  • 0

[.net]監控檔案系統的目錄變更或檔案變更(FileSystemWatcher)

使用FileSystemWatcher這個class就對囉

public partial class Form1 : Form
{
	
	FileSystemWatcher fsw;

	#region Form Load

	public Form1()
	{
		InitializeComponent();
	}

	private void Form1_Load(object sender, EventArgs e)
	{
		//要監控的資料夾
		fsw = new FileSystemWatcher(@"C:\message\CollectorWorker_Log_Live-1\Message\2017\03\22");
		btnStart.Enabled = true;
		btnStop.Enabled = false;
	}

	#endregion

	#region click事件

	//開始監控
	private void btnStart_Click(object sender, EventArgs e)
	{
		//是否監控子目錄
		fsw.IncludeSubdirectories = true;

		//設定所要監控的變更類型
		//不註明就是全部都監控
		fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

		//設定所要監控的檔案,ex:*.txt
		fsw.Filter = "*.*";
		
		//Created, Changed, Deleted, Renamed....更多可上msdn查詢
		fsw.Created += new FileSystemEventHandler(fsw_Created);

		//允許觸發事件
		fsw.EnableRaisingEvents = true;

		btnStart.Enabled = false;
		btnStop.Enabled = true;
	}

	//停止監控
	private void btnStop_Click(object sender, EventArgs e)
	{
		fsw.EnableRaisingEvents = false;

		fsw.Created -= new FileSystemEventHandler(fsw_Created);
		fsw.Dispose();

		btnStop.Enabled = false;
		btnStart.Enabled = true;
	}

	#endregion

	#region 事件

	private void fsw_Created(object sender, FileSystemEventArgs e)
	{            
		MessageBox.Show(e.Name + "  " + e.ChangeType + "  " + e.FullPath);
	}



	#endregion


 
}

執行結果:

大概是這樣………

參考文章:
FileSystemWatcher 類別應用實例
https://dotblogs.com.tw/dotnetfactory/archive/2008/04/10/2780.aspx
C# - 使用 FileSystemWatcher 來監控資料夾下的文件
https://dotblogs.com.tw/dc690216/archive/2010/09/18/17801.aspx
FileSystemWatcher -- 當目錄或目錄內的檔案變更時,接聽 (Listen) 檔案系統變更告知並引發事件
https://dotblogs.com.tw/mis2000lab/archive/2009/03/17/filesystemwatcher_20090317.aspx