tags:

views:

552

answers:

3

Hi,

I have a requirement to move certain files after they has been processed. Another process access the file and I am not sure when it releases them. Is there any way I can find out when the handle to the file has been released so I can move them at that time.

I am using Microsoft C# and .Net framework 3.5.

Cheers, Hamid

A: 

Just contniually try to open the file for exclusive writing? (e.g. pass FileShare.None to the FileStream constructor). Once you have opened it, you know no one else is using it. However, this might not be the best way to do what you're doing.

If you're after two way communication, see if the other program can be talked to via a pipe.

Pod
This does involve try/catching when creating the FileStream, doesn't it? There must be a better solution, but I can't find it either :-/
tobsen
+2  A: 

Hi Hamid, If you have control of both the producer of the file and the consumer, the old trick to use is create the file under a different name, and rename it once complete. For example, say the producer is creating files always called file_.txt, and your consumer is scanning for all files beginning file_, then the producer can do this: 1. Create the file called tmpfile_.txt 2. When the file is written, the producer simply renames the file to file_.txt

The rename operation is atomic, so once your consumer sees its available, it is safe to open it.

Of course, this answer depends on if you are writing both programs.

HTH Dermot.

dermdaly
A: 

If you have control of both of the sources, use a named mutex (which works across processes) to control access to the files rather than locking the file at the filesystem level. This way, you don't have to catch the exception raised by attempting to lock a locked file and loop on that, which is rather inelegant.