C# FileSystemWatcher 監視資料夾和檔案變更

使用FileSystemWatcher監視資料夾或檔案變更

有變更時會呼叫FileChanged,使用 e.FullPath可以取得變動的檔案路徑

    private FileSystemWatcher _fileSystemWatcher;
private string monitorPath = "D:\\";

public void Monitor()
{
try
{
if (_fileSystemWatcher == null) _fileSystemWatcher = new FileSystemWatcher();

_fileSystemWatcher.Path = monitorPath;
_fileSystemWatcher.NotifyFilter =
NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.CreationTime;

_fileSystemWatcher.IncludeSubdirectories = false;
_fileSystemWatcher.EnableRaisingEvents = true;


_fileSystemWatcher.Changed += FileChanged; //檔案屬性變更、建立的檔案和刪除的檔案
_fileSystemWatcher.Renamed += FileChanged; //重新命名檔案和資料夾的舊路徑和新路徑
}
catch (Exception exception)
{
}
}

private void FileChanged(object sender, FileSystemEventArgs e)
{
string filePath = e.FullPath;
Console.WriteLine("變動的檔案:" + filePath);
}
}

補充:
_fileSystemWatcher_scanHistoryPath.IncludeSubdirectories = false; //監視子目錄
_fileSystemWatcher_scanHistoryPath.EnableRaisingEvents = true; //開始監視


注意:當檔案變更時FileChanged可能會被多次呼叫!

其原因是因為包括檔名、屬性、日期等檔案資訊都會被變更

stackoverflow上面也有許多討論和解法,但都不那麼管用

最好的方式就是寫個List(或Dictionary)

可以參考我這篇C# FileSystemWatcher 監視檔案變更 去除重複


留言