4

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 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
Database Guy
  • 51
  • 1
  • 2

3 Answers3

6

It's simple, use FileSystemWatcher.

Adi
  • 5,113
  • 6
  • 46
  • 59
  • 2
    Be aware that the FileSystemWatcher (and the underlying Win32 API) does not cope well with network files see - http://stackoverflow.com/questions/151804/system-io-filesystemwatcher-to-monitor-a-network-server-folder-performance-cons – Adam Straughan Apr 04 '11 at 20:39
  • 1
    @adam straughan Yes, thanks for pointing this out. @user691770 can you please specify if it's a local or network file? – Adi Apr 04 '11 at 20:50
5

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

ChrisW
  • 9,151
  • 1
  • 20
  • 34
4

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.

Rafal Spacjer
  • 4,838
  • 2
  • 26
  • 34