tags:

views:

690

answers:

3

Is there a built in method for waiting for a file to be created in c#? How about waiting for a file to be completely written?

I've baked my own by repeatedly attempting File.OpenRead() on a file until it succeeds (and failing on a timeout), but spinning on a file doesn't seem like the right thing to do. I'm guessing there's a baked-in method in .NET to do this, but I can't find it.

+6  A: 

What about using the FileSystemWatcher component ?

This class 'watches' a given directory or file, and can raise events when something (you can define what) has happened.

Frederik Gheysels
Just a caution with FileSystemWatcher - I've found that a FileSystemWatcher can fail when attempting to use it with a drive mounted on the network where the connection is flaky. Essentially, when the connection was lost and reestablished, the watcher no longer recognized changes. Just my two cents.
itsmatt
It also doesn't work with Novell Networks at least 1.1 didn't
JoshBerke
+1  A: 

FileSystemWatcher can notify you when a file is created, deleted, updated, attributes changed etc. It will solve your first issue of waitign for it to be created.

As for waiting for it to be written, when a file is created, you can spin off and start tracking it's size and wait for it stop being updated, then add in a settle time period, You can also try and get an exclusive lock but be careful of locking the file if the other process is also trying to lock it...you could cause unexpected thigns to occur.

JoshBerke