Detect newly created file, just edited file

I try to read the file in a timely manner at the time of creation or creation. There is another piece of hardware that creates files in a folder that I want to access (in a timely manner).

How to search for a new edited or created file using C # .net. I do not want to periodically try this folder, because the machine can potentially write several times between the polling interval. that is, I want to avoid:

  • File 1 (created) 10:00:04
  • Poll file 1 (no data loss) 10:00:05
  • File 1 (overwritten with new data) 10:00:07 AM
  • Poll file 1 (no data) 10:00:10 AM
  • File 1 (overwritten with new data) 10:00:12 AM
  • File 1 (overwritten with new data) 10:00:14 AM
  • Poll file 1 (10:00:12 a.m. lost) 10:00:15 AM
+4
source share
3 answers

It is simple, use FileSystemWatcher .

+6
source

I think the FileSystemWatcher class will give you what you are looking for.

+5
source

You can use the FileSystemWatcher class. It allows you to view a specific directory (you can also apply a filter to the file type), and if the file is modified, the event will be raised.

Here you have a sample code from msdn :

// Create a new FileSystemWatcher and set its properties. FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = args[1]; /* Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories. */ watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. watcher.Filter = "*.txt"; // Add event handlers. watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new FileSystemEventHandler(OnChanged); watcher.Renamed += new RenamedEventHandler(OnRenamed); // Begin watching. watcher.EnableRaisingEvents = true; 

where OnChanged and OnRenamed are event handlers with your logic.

+4
source

Source: https://habr.com/ru/post/1346617/


All Articles