利用windows系統自帶的API檢測文件的修改/刪除/新建/重命名


這個接口是比較好用的,不需要第三方的dll,只需要system.IO引入了就可以使用了

修改/刪除/新建/重命名這幾種對文件的操作都能夠被監測到

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Configuration;

namespace ReadExcel.Common
{
    class FileWatcher
    {
        public void Watcher()
        {

            FileSystemWatcher watcher = new FileSystemWatcher();

            watcher.Path = ConfigurationManager.AppSetting("Detach");

            watcher.NotifyFilter = NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName;

            watcher.Filter = "*";

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(this.OnChanged);
            watcher.Created += new FileSystemEventHandler(this.OnChanged);
            watcher.Deleted += new FileSystemEventHandler(this.OnChanged);
            watcher.Renamed += new RenamedEventHandler(this.OnRenamed);

            // Begin watching.
            watcher.EnableRaisingEvents = true;

        }
        private void OnChanged(object source, FileSystemEventArgs e) =>
            Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");

        private void OnRenamed(object source, RenamedEventArgs e) =>
            Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
    }


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM