开发者

Detect newly created file, just edited file

开发者 https://www.devze.com 2023-02-22 14:42 出处:网络
I am trying to read a file on a timely basis the moment an edit or creation occurs.There is another piece of hardware that creates files to a folder which i wish to access (on a timely basis).

I am trying to read a file on a timely basis the moment an edit or creation occurs. There is another piece of hardware that creates files to a folder which i wish to access (on a timely basis).

How does one go about detecting the creation a newly edited or created开发者_JAVA技巧 file using C# .net. I do not want to poll the folder on a periodic basis as the machine could potentially write several times in between the polling time interval. i.e. I want to avoid:

  • File 1 (created) 10:00:04AM
  • Poll file 1 ( no data lost ) 10:00:05AM
  • File 1 (overwritten with new data) 10:00:07AM
  • Poll File 1 ( no data lost ) 10:00:10AM
  • File 1 (overwritten with new data) 10:00:12AM
  • File 1 (overwritten with new data) 10:00:14AM
  • Poll File 1 ( 10:00:12AM data lost) 10:00:15AM


It's simple, use FileSystemWatcher.


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


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

Here you have 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 events handlers with your logic.

0

精彩评论

暂无评论...
验证码 换一张
取 消