views:

100

answers:

3

Hi,

I need to write some code that will copy file from directory when the file will change.

I know C/C++ (little bit :]) but I never used .net. Am I thinkig good? First I create new thread with FSW and then when change will occur create next thread that will copy file?

+1  A: 

A pattern for what you describe is to have one thread watching the file using the FileSystemWatcher, and inserting an event (or the file) onto a queue, whilst another thread reads the queue and actions the events.

Mitch Wheat
A: 

You are on the right track, as file system watching is an OS feature. You can use it in .NET or directly in native C++. .NET provides a simpler programming model.

Note that depending on your requirements, you could use Robocopy (included in at least Vista) which can monitor a directory and copy files automatically.

Timores
+1  A: 

If you are comfortable with C/C++ then you should use ReadDirectoryChangesW(). FileSystemWatcher is a thin wrapper around this API function. But undeniably easier to get going. Sample SDK code is available here.

The usual problem with FSW/RDC is that you can't access the file when you get a notification because the app that's writing the file has a lock on it. You'd need a thread-safe queue to store notifications, emptied by another thread that periodically tries to perform the required operation. This is also a healthy approach when processing the notifications, you'll want to spend as little time as possible to avoid having to create large notification buffers. They are an expensive system resource.

Hans Passant