C# - 使用 FileSystemWatcher 來監控資料夾下的文件

摘要:C# - 使用 FileSystemWatcher 來監控資料夾下的文件

FileSystemWatcher 是一個當目錄或目錄內檔案變更時,接聽 (Listen) 檔案系統變更告知並引發事件。會用到這類別,也是因為專案中要監控特別資料夾中的檔案是否有所變動。使用後發覺,真是一個好物,以下就來寫個小範例來介紹他...

步驟一:首先在 C:下建立資料夾與檔案



步驟二:建立一個新的 Winform 專案,並且設計一下畫面


步驟三:實作 FileSystemWatcher 功能

Code:

using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        FileInfo fi;
        StringBuilder sb;
        DirectoryInfo dirInfo;
        FileSystemWatcher _watch = new FileSystemWatcher();

        public Form1()
        {
            InitializeComponent();

            MyFileSystemWatcher();
        }

        private void MyFileSystemWatcher()
        {
            //設定所要監控的資料夾
            _watch.Path = @"C:\張小呆文件夾";
           
            //設定所要監控的變更類型
            _watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

            //設定所要監控的檔案
            _watch.Filter = "*.TXT";

            //設定是否監控子資料夾
            _watch.IncludeSubdirectories = true;

            //設定是否啟動元件,此部分必須要設定為 true,不然事件是不會被觸發的
            _watch.EnableRaisingEvents = true;

            //設定觸發事件
            _watch.Created += new FileSystemEventHandler(_watch_Created);
            _watch.Changed += new FileSystemEventHandler(_watch_Changed);
            _watch.Renamed += new RenamedEventHandler(_watch_Renamed);
            _watch.Deleted += new FileSystemEventHandler(_watch_Deleted);
        }

        /// <summary>
        /// 當所監控的資料夾有建立文字檔時觸發
        /// </summary>
        private void _watch_Created(object sender, FileSystemEventArgs e)
        {
            sb = new StringBuilder();

            dirInfo = new DirectoryInfo(e.FullPath.ToString());

            sb.AppendLine("新建檔案於:" + dirInfo.FullName.Replace(dirInfo.Name, ""));
            sb.AppendLine("新建檔案名稱:" + dirInfo.Name);
            sb.AppendLine("建立時間:" + dirInfo.CreationTime.ToString());
            sb.AppendLine("目錄下共有:" + dirInfo.Parent.GetFiles().Count() + " 檔案");
            sb.AppendLine("目錄下共有:" + dirInfo.Parent.GetDirectories().Count() + " 資料夾");

            MessageBox.Show(sb.ToString());
        }

        /// <summary>
        /// 當所監控的資料夾有文字檔檔案內容有異動時觸發
        /// </summary>
        private void _watch_Changed(object sender, FileSystemEventArgs e)
        {
            sb = new StringBuilder();

            dirInfo = new DirectoryInfo(e.FullPath.ToString());

            sb.AppendLine("被異動的檔名為:" + e.Name);
            sb.AppendLine("檔案所在位址為:" + e.FullPath.Replace(e.Name, ""));
            sb.AppendLine("異動內容時間為:" + dirInfo.LastWriteTime.ToString());

            MessageBox.Show(sb.ToString());
        }

        /// <summary>
        /// 當所監控的資料夾有文字檔檔案重新命名時觸發
        /// </summary>
        private void _watch_Renamed(object sender, RenamedEventArgs e)
        {
            sb = new StringBuilder();

            fi = new FileInfo(e.FullPath.ToString());

            sb.AppendLine("檔名更新前:" + e.OldName.ToString());
            sb.AppendLine("檔名更新後:" + e.Name.ToString());
            sb.AppendLine("檔名更新前路徑:" + e.OldFullPath.ToString());
            sb.AppendLine("檔名更新後路徑:" + e.FullPath.ToString());
            sb.AppendLine("建立時間:" + fi.LastAccessTime.ToString());

            MessageBox.Show(sb.ToString());
        }

        /// <summary>
        /// 當所監控的資料夾有文字檔檔案有被刪除時觸發
        /// </summary>
        private void _watch_Deleted(object sender, FileSystemEventArgs e)
        {
            sb = new StringBuilder();

            sb.AppendLine("被刪除的檔名為:" + e.Name);
            sb.AppendLine("檔案所在位址為:" + e.FullPath.Replace(e.Name, ""));
            sb.AppendLine("刪除時間:" + DateTime.Now.ToString());

            MessageBox.Show(sb.ToString());
        }

        private void btn_Before_Click(object sender, EventArgs e)
        {
            ReadTextFile(txtBefore);
        }

        private void btn_After_Click(object sender, EventArgs e)
        {
            ReadTextFile(txtAfter);
        }

        /// <summary>
        /// 將文字檔內容顯示於所指定的 TextBox
        /// </summary>
        /// <param name="p_TextBox">所指定的 TextBox</param>
        private void ReadTextFile(TextBox p_TextBox)
        {
            sb = new StringBuilder();

            string[] Txt_All_Lines = System.IO.File.ReadAllLines(@"C:\張小呆文件夾\ABC.txt", Encoding.Default);

            foreach (string Single_Line in Txt_All_Lines)
            {
                sb.AppendLine(Single_Line);
            }

            p_TextBox.Text = sb.ToString();
        }
    }
}

結果:

1.在資料夾中建立一個新的檔案,建立後會觸發 FileSystemWatcher 所提供的事件


2.對剛建立的檔案重新命名,重新命名後會觸發 FileSystemWatcher 所提供的事件


3.刪除重新命名的檔案,刪除後會觸發 FileSystemWatcher 所提供的事件


4.更改 ABC.txt 檔案中的內容,更改後會觸發 FileSystemWatcher 所提供的事件






參考:
FileSystemWatcher 類別
C# FileSystemWatcher控件的使用方法
How to: Read From a Text File (C# Programming Guide)